(思维分析)12th浙江省赛,D.Beauty of Array

来源:互联网 发布:数据库管理好学吗 编辑:程序博客网 时间:2024/05/16 06:29

Beauty of Array

Time Limit: 2 Seconds      Memory Limit: 65536 KB

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

/*题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3872题意:定义:一个序列的beauty为序列不重复元素之和。给一个序列A,求A所有连续子序列的beauty之和。分析:感觉主要是仔细分析,并没有什么成名的算法。  从前往后扫,对每一个(后面称为“层”)当前元素ai分析以它为结尾的连续子串对答案的贡献,发现  ①当前层对答案的贡献跟上一层对答案的贡献有关。  ②如果ai出现过,则对答案的贡献跟前面最近一个ai的角标有关系。注意:使用int型index[]时,提交后PE,原因是有index()这么一个函数;故需要修改这个数组的名字。*/#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>using namespace std;typedef long long LL;const int maxn = 100005;const int maxval = 1000005;bool vis[maxval];int index0[maxval];int N;void init(){for (int i = 0; i <= N; i++)vis[i] = false;}int main(){int T;scanf("%d", &T);while (T--){scanf("%d", &N);init();LL ans = 0, pre = 0, cur = 0;int a;for (int i = 1; i <= N; i++){scanf("%d", &a);if (vis[a] == true)//如果ai在前面已经出现过{cur = pre + a*i - a*index0[a];//计算当前第i层对答案的贡献ans += cur;//当前第i层对答案贡献加到答案中index0[a] = i;//序列中值为ai的元素『当前』最后一次出现的角标为i}else//如果ai第一次出现{cur = pre + a*i;//计算当前第i层对答案的贡献ans += cur;//当前第i层对答案贡献加到答案中vis[a] = true;//标记值为ai的元素出现了index0[a] = i;//序列中值为ai的元素第一次出现的角标为i}pre = cur; //当前第层对答案的贡献 作为 下一层计算的 前一层对答案的贡献}//cout<<ans<<endl;printf("%lld\n", ans);}return 0;}



0 0