C. Sequence Pair Weight

传送门

The weight of a sequence is defined as the number of unordered pairs of indexes (i,j)(here i<j) with same value (ai=aj). For example, the weight of sequence a=[1,1,2,2,1] is 4. The set of unordered pairs of indexes with same value are (1,2)(1,5), (2,5), and (3,4)

You are given a sequence aa of nn integers. Print the sum of the weight of all subsegments of aa.

A sequence bb is a subsegment of a sequence aa if bb can be obtained from aa by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Input

Each test contains multiple test cases. The first line contains the number of test cases t (1t105). Description of the test cases follows.

The first line of each test case contains a single integer n (1n105.

The second line of each test case contains nn integers a1,a2,,an (1ai1e9).

It is guaranteed that the sum of nn over all test cases does not exceed 1e5.

Output

For each test case, print a single integer — the sum of the weight of all subsegments of a.

It is guaranteed that the sum of nn over all test cases does not exceed 1e5

 
Example
input
Copy
2
4
1 2 1 1
4
1 2 3 4
output
Copy
6
0
Note
  • In test case 11, all possible subsegments of sequence [1,2,1,1]having size more than 11 are:
    1. [1,2][ having 0 valid unordered pairs;
    2. [2,1] having 0 valid unordered pairs;
    3. [1,1][having 1 valid unordered pair;
    4. [1,2,1] having 1 valid unordered pairs;
    5. [2,1,1]having 1 valid unordered pair;
    6. [1,2,1,1] having 3 valid unordered pairs.
    Answer is 66.
  • In test case 22, all elements of the sequence are distinct. So, there is no valid unordered pair with the same value for any subarray. Answer is 00.
  • 题意:给一个数组,求他的所有连续子串中,任取相等的两数的方案之和。

    题解:这个题其实,造个全是1的数组乱搞算出来就差不多了。

    当计算i的贡献时,我们计算前面所有a[i]的贡献,同时对于每一个包含i的后缀都可以算一次i前面的贡献,所以ans加上map[a[i]]*(n-i+1);

    当a[i]在第i个位置时,可为后面的数贡献i个子串,所以每次算完贡献后我们在map[a[i]]中加i

#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
typedef long long ll;
const int maxn=1e6+100;
map<int,ll>mp;
int main(){
    int t;
    cin>>t;
    while(t--){
        mp.clear();
        int n;
        cin>>n;
        ll ans=0;
        int x;
        for(int i=1;i<=n;i++){
            cin>>x;
            ans+=(mp[x]*(n-i+1));
            mp[x]+=i; 
        }
        printf("%lld\n",ans);
    }
}

 

posted @ 2021-05-24 23:18  lipu123  阅读(171)  评论(0)    收藏  举报