P2709 小B的詢問[莫隊]
阿新 • • 發佈:2018-12-09
直接莫隊
#include<bits/stdc++.h> #define N 50050 #define LL long long using namespace std; int pos[N],a[N],n,m,k,cnt[N]; LL ans[N],now; struct Node{int l,r,id;}q[N]; bool cmp(Node a,Node b){ if(pos[a.l]==pos[b.l]) return a.r<b.r; return pos[a.l]<pos[b.l]; } void del(int x){now -= (LL)cnt[x]*cnt[x]; cnt[x]--; now += (LL)cnt[x]*cnt[x];} void add(int x){now -= (LL)cnt[x]*cnt[x]; cnt[x]++; now += (LL)cnt[x]*cnt[x];} int main(){ cin>>n>>m>>k; int siz=sqrt(n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); for(int i=1;i<=n;i++) pos[i]=i/siz; for(int i=1;i<=m;i++) scanf("%d%d",&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++){ while(r<q[i].r) add(a[++r]); while(r>q[i].r) del(a[r--]); while(l>q[i].l) add(a[--l]); while(l<q[i].l) del(a[l++]); ans[q[i].id] = now; } for(int i=1;i<=m;i++) printf("%lld\n",ans[i]); }