P2709 小B的询问
题目链接
这题主要的就是对一个静态的序列进行很多次的询问。在一定的方面上这些询问是可以相互转化得到的,并且可能有些被询问的区间之间还有重叠部分,于是我们就可能会想到用莫队写这题。另外,此题中,
Talk is cheap, show you the code .
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,k,a[50005],cur,anss[50005];
struct node{
int l,r,id;
}q[50005];
int ans,cnt[50005];
bool cmp(node aa,node bb){
return aa.l/cur == bb.l/cur ? aa.r/cur < bb.r/cur : aa.l/cur < bb.l/cur;
}
int dx(int x){
return x*x;
}
void add(int x){
int y=dx(cnt[a[x]]);
++cnt[a[x]];
ans=ans+dx(cnt[a[x]])-y;
}
void del(int x){
int y=dx(cnt[a[x]]);
--cnt[a[x]];
ans=ans+dx(cnt[a[x]])-y;
}
signed main(){
std::ios::sync_with_stdio(false);
cin.tie();cout.tie();
cin>>n>>m>>k;
cur=(int)(sqrt(n));
for(int i=1;i<=n;++i)
cin>>a[i];
for(int i=1;i<=m;++i)
cin>>q[i].l>>q[i].r,q[i].id=i;
sort(q+1,q+m+1,cmp);
int l=1,r=0;
for(int i=1;i<=m;++i){
int ll=q[i].l,rr=q[i].r;
while(r>rr)
del(r--);
while(r<rr)
add(++r);
while(l<ll)
del(l++);
while(l>ll)
add(--l);
anss[q[i].id]=ans;
//cout<<l<<" "<<r<<endl;
//cout<<q[i].id<<" "<<ans<<endl;
}
for(int i=1;i<=m;++i)
cout<<anss[i]<<endl;
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】