ZOJ-3972 Beauty of Array

来源:互联网 发布:大乐斗门派心法数据 编辑:程序博客网 时间:2024/06/05 10:16

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

3
5
1 2 3 4 5
3
2 3 3
4
2 3 3 2

Sample Output

105
21
38

题意:一串数字序列,计算
【序列中所有
【子串(连续)(包括该序列本身)里的数字(重复的数字只算一次)的和】
的和】
嗯,希望不会被绕晕。。。

对于一个序列X,假设这个序列无重复数字。
当这个序列后面加上一个与前面不重复的数A时,会构成一些新的子串序列。
新的子串序列即【前面的序列+A】这样的结构。
也就是,新构成的序列比前面多的就是新加上的A;
当A不重复的时候,每构成一个序列,就多一个A。
能与A一起构成新连续序列的旧序列,一定是以旧序列中某一个数开头,以旧序列中最后一个数结尾。
【123+4 新增子序列 123+4、23+4、3+4、4 】
新序列的值即 旧序列的值+n*A 【n,新子串的数目】

若序列中有重复数字,对于旧序列中包含A的部分,新出现的A没有意义,不会再加A。
那么用一个map[A],存储A最后出现的位置,那么这个位置后面的部分是没有A的,这部分和A构成的子串是新的。
所以新子串是后面不含A部分和A构成的,计算数目加入即可。

#include<iostream>#include<cstring>#include<string>#include<map>#include<algorithm>#include<stdio.h>#define Max 100000using namespace std;int main(){    int i, j, k, t;    int T, n;    int tmp;    long long sum, ans;    map<int, int> mp;    while (cin >> T)    {        for (i = 0; i < T; i++)        {            mp.clear();            cin >> n;            sum = 0;            ans = 0;            for (j = 1; j <= n; j++)            {                cin >> tmp;                if (mp[tmp])//tmp在前面出现过                    sum += (j - mp[tmp])*tmp;//加入tmp后新增的子串数*tmp                else//tmp首次出现                    sum += j*tmp;                ans += sum;                mp[tmp] = j;//标记tmp最后出现的位置            }            cout << ans << endl;        }    }    return 0;}
0 0