♥ZOJ 3872-Beauty of Array【规律】

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

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

Sample Output

105
21

38

解题思路:

这是一道规律题,我们要找到一个子序列(其中重复的我们只算一次),这个序列是相邻的。

3

2 3 3这组数据 我们分析一下。

序列只有一个元素:2 3 3 =8

序列有两个元素:23 33 =8

序列有三个元素:233 =5 5+8+8=21

我们一位一位的来画这个三角形就可以看出,元素在下一个新增的数后与上一次这个数出现的位置有关。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll; 
ll dian[1005000];
ll dp[1005000];
int main()
{
	ll t;
	scanf("%lld",&t);
	while(t--)
	{
		memset(dian,0,sizeof(dian));
		ll n;
		scanf("%lld",&n);
		dp[0]=0;
		for(ll i=1;i<=n;i++)
		{
			ll xx;
			scanf("%lld",&xx);
			dp[i]=(dp[i-1]+xx)+(i-1-dian[xx])*xx;
			dian[xx]=i;
		}
		ll ans=0;
		for(ll j=1;j<=n;j++)
		{
			ans+=dp[j];
		}
		printf("%lld\n",ans);
	}
	return 0;
}


你可能感兴趣的:(ZOJ,规律)