ZOJ 3827 Beauty of Array

来源:互联网 发布:凡高网络 编辑:程序博客网 时间:2024/06/14 08:31

Description

Edward has an array A with N integers. He defines the beauty of an array as the summation of all distinct integers in the array. Now Edward wants to know the summation of the beauty of all contiguous subarray of the array A.

Input

There are multiple test cases. The first line of input contains an integer T indicating the number of test cases. For each test case:

The first line contains an integer N (1 <= N <= 100000), which indicates the size of the array. The next line contains N positive integers separated by spaces. Every integer is no larger than 1000000.

Output

For each case, print the answer in one line.

Sample Input

351 2 3 4 532 3 342 3 3 2

Sample Output

1052138




这个题目的话就是要求我们这个数组的所有的连续的去重子序列的和sum,除看这个题目肯定会觉得这是一个O(N*N)的算法吧?

但是实际上并不需要那样计算,针对于第 i 个数,它被加进sum的次数是一个确定的。对吧?这个时候我们的任务就是去计算被加的次数是多少不就好了?

那么一个数被加的次数到底该怎么计算呢?

由于这个题目要求一个序列中不能让相同的元素加多次,故针对于当前的第 i 个数加入之前第 k 个数与其相同的话,那么k之前的数的子序列都不会用到第 i 个数对吗?

故,用到第 i 个数的只有在 i - k 这个序列的元素才会用到对吗?  且 i 后面每有一个元素,第 i 个数都需要再被加 i - k 次对吗?  故这时候规律就出来了。。

下面给出代码:


#include<cstring>#include<cstdio>int pos[100005];int main(void){    int a,T,n,m,i;    long long sum,dp;    scanf("%d",&T);    while(T--){        scanf("%d",&n);        memset(pos,0,sizeof(pos));        sum=0;dp=0;        for(i=1;i<=n;i++){            scanf("%d",&a);            dp+=(i-pos[a])*a;            sum+=dp;            pos[a]=i;        }        printf("%lld\n",sum);    }}











0 0
原创粉丝点击