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的数对后,设它能覆盖到的子段的左端点记为l,右端点记为r,则l的范围为,r的范围为,所以能够覆盖到的总数就是。
对于本题我写的代码可以先把所有的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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!