【ZOJ3872】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

【题意】

将一个序列的子集不重复元素相加。

【解题思路】

  2 3 3 2
子集 (2) (2),(3),(2,3

(2),(3),(3),(2,3),(3,3),(2,3,3)

(2),(3),(3),(2),(2,3),(3,3),(3,2),(2,3,3),(3,3,2),(2,3,3,2)
sum 2 3*2+2=8 3*1+8=11 2*3+11=17
ans 2 10 21 38

(多出的个数已加粗)

以2 3 3 2为例,当计算以2为最后一位的子集和为2,计算以3为最后一位的子集和时,会发现比前一个状态多加了2个3,然后再将前一个状态的子集和累加,就是以前两个元素所有的子集和,以此类推,再把每个状态的子集和累加即是答案。


【代码】

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn=1e5+5;
int a[maxn];
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        memset(a,0,sizeof(a));
        int n;
        LL sum=0,ans=0;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            int x;
            scanf("%d",&x);
            sum+=(i-a[x])*x;
            ans+=sum;
            a[x]=i;
        }
        printf("%lld\n",ans);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39826163/article/details/81949569