ZOJ-3972 Beauty of Array

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

题意:一串数字序列,计算
【序列中所有
【子串(连续)(包括该序列本身)里的数字(重复的数字只算一次)的和】
的和】
嗯,希望不会被绕晕。。。

对于一个序列X,假设这个序列无重复数字。
当这个序列后面加上一个与前面不重复的数A时,会构成一些新的子串序列。
新的子串序列即【前面的序列+A】这样的结构。
也就是,新构成的序列比前面多的就是新加上的A;
当A不重复的时候,每构成一个序列,就多一个A。
能与A一起构成新连续序列的旧序列,一定是以旧序列中某一个数开头,以旧序列中最后一个数结尾。
【123+4 新增子序列 123+4、23+4、3+4、4 】
新序列的值即 旧序列的值+n*A 【n,新子串的数目】

若序列中有重复数字,对于旧序列中包含A的部分,新出现的A没有意义,不会再加A。
那么用一个map[A],存储A最后出现的位置,那么这个位置后面的部分是没有A的,这部分和A构成的子串是新的。
所以新子串是后面不含A部分和A构成的,计算数目加入即可。

#include<iostream>
#include<cstring>
#include<string>
#include<map>
#include<algorithm>
#include<stdio.h>
#define Max 100000

using namespace std;

int main()
{
    int i, j, k, t;
    int T, n;
    int tmp;
    long long sum, ans;
    map<int, int> mp;
    while (cin >> T)
    {
        for (i = 0; i < T; i++)
        {
            mp.clear();
            cin >> n;
            sum = 0;
            ans = 0;
            for (j = 1; j <= n; j++)
            {
                cin >> tmp;
                if (mp[tmp])//tmp在前面出现过
                    sum += (j - mp[tmp])*tmp;//加入tmp后新增的子串数*tmp
                else//tmp首次出现
                    sum += j*tmp;
                ans += sum;
                mp[tmp] = j;//标记tmp最后出现的位置
            }
            cout << ans << endl;
        }
    }
    return 0;
}
04-27 2014
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值