Loading

Codeforces Round #721 (Div. 2) C. Sequence Pair Weight(计算贡献/STL)

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 𝑎=[1,1,2,2,1]a=[1,1,2,2,1] is 44. The set of unordered pairs of indexes with same value are (1,2)(1,2), (1,5)(1,5), (2,5)(2,5), and (3,4)(3,4).

You are given a sequence 𝑎a of 𝑛n integers. Print the sum of the weight of all subsegments of 𝑎a.

A sequence 𝑏b is a subsegment of a sequence 𝑎a if 𝑏b can be obtained from 𝑎a 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 (1≤𝑡≤1051≤t≤105). Description of the test cases follows.

The first line of each test case contains a single integer 𝑛n (1≤𝑛≤1051≤n≤105).

The second line of each test case contains 𝑛n integers 𝑎1,𝑎2,…,𝑎𝑛a1,a2,…,an (1≤𝑎𝑖≤1091≤ai≤109).

It is guaranteed that the sum of 𝑛n over all test cases does not exceed 105105.

Output

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

Example

input

Copy

2
4
1 2 1 1
4
1 2 3 4

output

Copy

6
0

大意就是给定一个序列,让你求出来它的所有子段的权值的和,一个连续段的权值和定义为这里面的满足\(a[i]=a[j], i < j\)\((i, j)\)的数量。

很容易可以想到直接计算贡献当我们知道一个对应于同一个a的数对后,设它能覆盖到的子段的左端点记为l,右端点记为r,则l的范围为\([1, i]\),r的范围为\([j, n]\),所以能够覆盖到的总数就是\(i\times (n - j + 1)\)

对于本题我写的代码可以先把所有的a离散化然后用桶存储离散化后每个a值的位置,预处理出前缀和然后倒着遍历每个桶,枚举j然后直接利用前缀和计算j为数对第二个数的所有数对对于答案的总贡献。然后FST了,GG。

放一个好哥哥写的简洁代码:

//C
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN=100009;
map<ll,ll> m;
int main(){
	int t,n;
	ll a[MAXN];
	ll ans;
	cin>>t;
	while(t--){
		ans=0;
		cin>>n;
		m.clear();
		for(int i=1;i<=n;i++){
			cin>>a[i];
		}
		for(int i=1;i<=n;i++){
			ans+=m[a[i]]*(n-i+1);
			m[a[i]]+=i;
		}
		cout<<ans<<endl;
	}
	return 0;
}
posted @ 2021-05-21 08:31  脂环  阅读(137)  评论(0编辑  收藏  举报