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.
There are multiple test cases. The first line of input contains an integer Tindicating 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.
For each case, print the answer in one line.
3 5 1 2 3 4 5 3 2 3 3 4 2 3 3 2
105 21 38
题意:先定义一个最美数组的概念,就是说一个连续的数组中,不重复的数字的加和。
然后这道题是给你一个长度为n的数组,让你求这个数组的所有子最美数组的加和。
用一个cur数组标记当前元素上一次出现时的坐标是多少。这样一来递推公式如下:
dp[i] = dp[i-1] + (i-cur[p[i]])*p[i];
比如说
4
2 3 1 3
这个样例吧。
i = 1 dp[i] = 2; {2}
i = 2 dp[i] = dp[i-1]+(i-cur[p[i]])*p[i]; {23} , {3}
i = 3 dp[i] = dp[i-1]+(i-cur[p[i]])*p[i];
{123} , {3,1} , {1}
i = 4 dp[i] = dp[i-1]+(i-cur[p[i]])*p[i]; {123} , {3,1} , {13} , {3}
正因为最美数组的定义,子数组中的相同元素+一遍就OK了。所以记录第一次出现的坐标。
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <stack>
#include <map>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
#define MAX_N 100005
#define INF 0x3f3f3f3f
#define Mem(a,x) memset(a,x,sizeof(a))
#define ll long long
ll dp[MAX_N];
int p[MAX_N],cur[MAX_N*10];
int main()
{
int n;
cin>>n;
while(n--) {
int m;
cin>>m;
Mem(dp,0);
Mem(cur,0);
for(int i = 1; i<=m; i++) {
cin>>p[i];
}
for(int i = 1; i<=m; i++) {
//cout<<i<<' '<<cur[p[i]]<<endl;
dp[i] = dp[i-1] + (i-cur[p[i]])*p[i];
cur[p[i]] = i;
}
ll ans = 0;
for(int i = 1; i<=m; i++) {
ans += dp[i];
// cout<<dp[i]<<endl;;
}
printf("%lld\n",ans);
}
return 0;
}