您的位置:首页 > 其它

ZOJ-3872-Beauty of Array【数学】【12th浙江省赛】

2016-01-27 00:00 399 查看

ZOJ-3872-Beauty of Array

[code]                    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

题目链接:ZOJ-3872

题目大意:给出n个数字的序列,求所有连续的子序列,不同数字的和。

题目思路:dp[i] //表示以数字i结尾的子序列的和

dp[i] = dp[i - 1] + (i - pos[num[i]]) * num[i]; //dp[i]等于以i-1结尾的子序列的和,加上把前面(i - pos[num[i]])个子序列后面都加上num[i].

eg: 1 2 3 4 | 2

以最后一个2结尾的子序列和为例,(一个子序列中出现相同数字,该数字只加一次)

[code]1 + 2 + 3 + 4 + 2, (前面出现过2,所以最后一个2不加)
2 + 3 + 4 + 2,
3 + 4 + 2, (前面没出现过2,最后一个2加)
4 + 2,=
2,


pos[num[i]] //记录上一次出现num[i]的位置。

以下是代码:

[code]#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
int num[100010];
int pos[100010];
long long dp[100010];  //以i结尾的和 
int main(){
    int t;
    cin >> t;
    while(t--)
    {
        int n;
        scanf("%d",&n);
        memset(num,0,sizeof(num));
        memset(pos,-1,sizeof(pos));
        memset(dp,0,sizeof(dp));
        for (int i = 0; i < n; i++)
        {
            cin >> 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;  //更新i最后一次出现的位置
        }
        long long ans = 0;
        for (int i = 0; i < n; i++)
        {
            ans += dp[i];  //各个结尾的和即为答案
        }
        cout << ans << endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: