D - 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 Tindicating 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

题解:定义beauty值为1个数组中不相同的值的和,要找一个数组中所有连续子数组的beauty值之和。一般做肯定超时,那么我们来想下简单的思路:用sum数组记录以i为结尾的所有情况之和,pre[x]记录x出现的上一次的位置,那么从第1位到第i位x只能算i-pre[x]次,pre[x]=0即为i次,其他的再加上sum[i-1]即保证了这次结果的正确性。(有点递推的意思了,知道上一位的关系后只需算出这一位的特殊情况再加和就可以了)。

#include<bits/stdc++.h>
using namespace std;
const int maxn=100010;
long long sum[maxn],pre[maxn];//long long 是重伤
int t,n,x;
long long ans;
int main()
{

    cin>>t;
    while(t--)
    {
        ans=0;
        memset(sum,0,sizeof(sum));
        memset(pre,0,sizeof(pre));
        cin>>n;
        for(int i=1;i<=n;i++)
        {
            cin>>x;
            sum[i]=sum[i-1]+(i-pre[x])*x;
            pre[x]=i;
            ans+=sum[i];
        }
        cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43824158/article/details/88986743