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
题意:给你n个数的集合,定义Beauty表示一个集合中不相等的数的和,求这个集合所有连续子序列的beauty的和。
一看都是得dp,dp的意思是以ai结尾的beauty的和,说两个样例。
①:1 2 3 4 5
子序列到1 的时候就他自己1
到2的时候有2, 1 2
到3的时候有3, 2 3, 1 2 3
到4的时候有4, 3 4, 2 3 4, 1 2 3 4
到5的时候有5, 4 5, 3 4 5, 2 3 4 5, 1 2 3 4 5
发现了吗,如果数都不相同,每次一个值能给总的beauty提供的次数是到这个数的集合长度。1能提供1次, 2是两次。。。。5是5次。
这个时候dp[n] = d[n-1] + an*n;
如果有相同的值呢???
②:2 3 3 2
到2的时候 2
到3的时候 3, 2 3
到3的时候 3, 3 3, 2 3 3
到2的时候 2, 3 2, 3 3 2, 2 3 3 2
看看这个时候能提供几次,对于到第二个3,前面的3在前面已经提供过beauty了,在有3也不算了。第二个2,实际上之提供了3次。
比如6 1 3 4 1 …1 假设最后一个1是第n个数,省略号中间没有1,最后这个1提供了几次呢??是n-5次,
…1
1…1
4 1…1
3 4 1…1
1 3 4 1…1
6 1 3 4 1 …1
第一次子序列里有1,就不再提供了。
#include <bits/stdc++.h>
using namespace std;
int a[111111];
int main()
{
ios::sync_with_stdio(false);
int t;
cin >> t;
while(t--)
{
int n, x;
cin >> n;
memset(a, 0, sizeof(a));
long long dp = 0, sum = 0;
for(int i = 1; i <= n; i++)
{
cin >> x;
dp+=(i-a[x])*x;
sum+=dp;
a[x] = i; //a里面存的是这个数字最后一次出现的地方。
}
cout << sum << endl;
}
return 0;
}