您的位置:首页 > 其它

ZOJ 3872 Beauty of Array【dp】

2016-04-18 21:42 369 查看
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
题目大意:给出n个数字的序列,求所有连续的子序列,不同数字的和。

比如样例2:

2 3 3

一共有这么些个子序列:(2)(3)(3)(2,3)(2,3,3)(3,3)

其中因为后两个子序列里边有重复的,所以最后output=(2)+(3)+(3)+(2,3)+(2,3)+(3)=21;

思路:

设dp【i】表示以num【i】结尾的子序列的和,辣么不难理解:

dp【i】=dp【i-1】+(i-pos【num【i】】)*num【i】;在上一个num【i】出现到i这个区间上都加上num【i】,因为num【i】之前出现过了,如果从0到i都加上num【i】,辣么久加重复了、

AC代码:
#include<stdio.h>
#include<string.h>
using namespace std;
int num[100010];
int pos[100010];
long long int dp[100010];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
memset(pos,-1,sizeof(pos));
memset(dp,0,sizeof(dp));
for(int i=0;i<n;i++)
{
scanf("%d",&num[i]);
}
dp[0]=num[0];
pos[num[0]]=0;
for(int i=1;i<n;i++)
{
dp[i]=dp[i-1]+(i - pos[num[i]]) * num[i];
pos[num[i]]=i;
}
long long sum=0;
for(int i=0;i<n;i++)
{
sum+=dp[i];
}
printf("%lld\n",sum);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ZOJ 3872