简单莫队
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int N=50010,M=200010,C=1000010; 4 int n,m,a[N],bel[N],siz,res,cnt[C],ans[M]; 5 struct Q{ 6 int l,r,id; 7 bool operator<(const Q& k)const{return bel[l]==bel[k.l]?r<k.r:l<k.l;} 8 }que[M]; 9 inline void expand(int k){ 10 if(!cnt[a[k]]) res++; 11 cnt[a[k]]++; 12 return; 13 } 14 inline void reduce(int k){ 15 cnt[a[k]]--; 16 if(!cnt[a[k]]) res--; 17 return; 18 } 19 int main(){ 20 scanf("%d",&n); 21 siz=pow((double)n,0.5); 22 for(int i=1;i<=n;i++) scanf("%d",&a[i]),bel[i]=(i-1)/siz+1; 23 scanf("%d",&m); 24 for(int i=1;i<=m;i++)scanf("%d%d",&que[i].l,&que[i].r),que[i].id=i; 25 sort(que+1,que+m+1); 26 int nowl=1,nowr=0; 27 for(int i=1;i<=m;i++){ 28 while(nowl>que[i].l){nowl--;expand(nowl);} 29 while(nowr<que[i].r){nowr++;expand(nowr);} 30 while(nowl<que[i].l){reduce(nowl);nowl++;} 31 while(nowr>que[i].r){reduce(nowr);nowr--;} 32 ans[que[i].id]=res; 33 } 34 for(int i=1;i<=m;i++) printf("%d\n",ans[i]); 35 return 0; 36 }