ZOJ 3872 浙江2015年省赛试题

D - Beauty of Array
Time Limit:2000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu

Description

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个数,
你求这n个数的子序列中不算重复的数的和,
比如第二个样例他的子序列就是
{2},{2,3},{2,3,3},{3},{3,3},{3};
但每个子序列中重复的元素不被算入,
所以他们的总和就是2+5+5+3+3+3=21;
dp[i]: 以第i个数结尾的所有子序列的和是多少。
那么这样我们就有了一个很简单的转移方法:
dp[i] = dp[i-1] + x[i] * (i - v[num[i]]);
v表示的是num[i]这个数字上一次出现在哪个位置,
这样可以确保不会重复计算
 
 
#include <cstdio>
#include <cstring>
#include <algorithm>
#include<math.h>
using namespace std;
#define max_v 100005
typedef long long LL;
LL dp[max_v];
LL sum;
LL num[max_v];
LL v[max_v];
void init()
{
    sum=0;
    memset(dp,0,sizeof(dp));
    memset(num,0,sizeof(num));
    memset(v,0,sizeof(v));
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        init();
        for(int i=1;i<=n;i++)
        {
            scanf("%lld",&num[i]);
        }
        for(int i=1;i<=n;i++)
        {
            dp[i]=dp[i-1]+(i-v[num[i]])*num[i];
            sum+=dp[i];
            v[num[i]]=i;
        }
        printf("%lld
",sum);
    }
    return 0;
}
/*

这个题的意识就是给你n个数,
你求这n个数的子序列中不算重复的数的和,
比如第二个样例他的子序列就是
{2},{2,3},{2,3,3},{3},{3,3},{3};
但每个子序列中重复的元素不被算入,
所以他们的总和就是2+5+5+3+3+3=21;

dp[i]: 以第i个数结尾的所有子序列的和是多少。

那么这样我们就有了一个很简单的转移方法:

dp[i] = dp[i-1] + x[i] * (i - v[num[i]]);

v表示的是num[i]这个数字上一次出现在哪个位置,

这样可以确保不会重复计算

*/

        


原文地址:https://www.cnblogs.com/yinbiao/p/9521958.html