传送门
根n分块,离线询问,先按块的编号排序,块内按r排序,莫队暴力更新答案。
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
const int max_n=5e4+5;
int n,m,k,t1,t2,ans;
int a[max_n],num[max_n],cnt[max_n],final[max_n];
struct hp{int l,r,ln,rn,id;}q[max_n];
inline int cmp(hp a,hp b){return a.ln<b.ln||a.ln==b.ln&&a.r<b.r;}
int main(){
scanf("%d%d%d",&n,&m,&k);
for (int i=1;i<=n;++i) scanf("%d",&a[i]);
t1=(int)sqrt(n);
if (n%t1==0) t2=n/t1; else t2=n/t1+1;
for (int i=1;i<=n;++i)
if (i%t1==0) num[i]=i/t1;
else num[i]=i/t1+1;
for (int i=1;i<=m;++i){
scanf("%d%d",&q[i].l,&q[i].r);
q[i].ln=num[q[i].l];
q[i].rn=num[q[i].r];
q[i].id=i;
}
sort(q+1,q+m+1,cmp);
for (int i=q[1].l;i<=q[1].r;++i) cnt[a[i]]++;
for (int i=1;i<=k;++i) ans+=cnt[i]*cnt[i];
final[q[1].id]=ans;
for (int i=2;i<=m;++i){
if (q[i].l<q[i-1].l)
for (int j=q[i-1].l-1;j>=q[i].l;--j){
ans-=cnt[a[j]]*cnt[a[j]];
++cnt[a[j]];
ans+=cnt[a[j]]*cnt[a[j]];
}
else if (q[i].l>q[i-1].l)
for (int j=q[i-1].l;j<q[i].l;++j){
ans-=cnt[a[j]]*cnt[a[j]];
--cnt[a[j]];
ans+=cnt[a[j]]*cnt[a[j]];
}
if (q[i].r<q[i-1].r)
for (int j=q[i-1].r;j>q[i].r;--j){
ans-=cnt[a[j]]*cnt[a[j]];
--cnt[a[j]];
ans+=cnt[a[j]]*cnt[a[j]];
}
else if (q[i].r>q[i-1].r)
for (int j=q[i-1].r+1;j<=q[i].r;++j){
ans-=cnt[a[j]]*cnt[a[j]];
++cnt[a[j]];
ans+=cnt[a[j]]*cnt[a[j]];
}
final[q[i].id]=ans;
}
for (int i=1;i<=m;++i)
printf("%d\n",final[i]);
}