ZOJ 3872 Beauty of Array(数学啊)

来源:互联网 发布:redis对比mysql的优势 编辑:程序博客网 时间:2024/06/06 00:50

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5520


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

Author: LIN, Xi
Source: The 12th Zhejiang Provincial Collegiate Programming Contest


题意:

给出一个集合,求每个子集合非重复元素的总和。

PS:

dp += (i-w[x])*x;

dp 表示当前输入的x前(包含x)的子序列的和;

每次新加一个x,那么他和上一次出现的同一个x之间的就是新增的,

w[x] = i; 记录的是前面一次x最后出现的位置;

模拟一下就知道了:

输入   1     2     3

dp      1     5     14

sum   1     6      20

w[i]     1     2      3


代码如下:

#include <cstdio>
#include <cstring>
int main()
{
    int t;
    int n;
    int w[100017];
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        int x;
        memset(w,0,sizeof(w));
        long long sum = 0, dp = 0;
        for(int i = 1; i <= n; i++)
        {
            scanf("%d",&x);
            dp += (i-w[x])*x;
            sum+=dp;
            w[x] = i;
        }
        printf("%lld\n",sum);
    }
    return  0;
}

1 0
原创粉丝点击