BZOJ 1878: [SDOI2009]HH的项链
题目:
https://www.lydsy.com/JudgeOnline/problem.php?id=1878
题解:
赤果果的莫队板子题,主要是orz一波博客https://www.cnblogs.com/Paul-Guderian/p/6933799.html
代码:
1 #include<bits/stdc++.h>
2
3 using namespace std;
4
5 const int maxn=500010;
6 int col[1000010],g[maxn],kuai[maxn];
7 int n,m,ans;
8
9 struct Q{
10 int l,r,ans,pos;
11 }q[maxn];
12
13 bool cm1(Q a,Q b){
14 return kuai[a.l]==kuai[b.l]?a.r<b.r:kuai[a.l]<kuai[b.l];
15 }
16
17 bool cm2(Q a,Q b){
18 return a.pos<b.pos;
19 }
20
21 void change(int pos,int add){
22 col[g[pos]]+=add;
23 if(!col[g[pos]]) ans--; if(col[g[pos]]==1&&add==1) ans++;
24 }
25
26 int main(){
27 scanf("%d",&n);
28 for(int i=1;i<=n;i++) scanf("%d",&g[i]);
29 scanf("%d",&m);
30 for(int i=1;i<=m;i++) scanf("%d%d",&q[i].l,&q[i].r),q[i].pos=i;
31 int big=sqrt(n); for(int i=1;i<=n;i++) kuai[i]=i/big+1;
32 sort(q+1,q+m+1,cm1); int l=1,r=0;
33 for(int i=1;i<=m;i++){
34 while(r<q[i].r) r++,change(r,1);
35 while(l>q[i].l) l--,change(l,1);
36 while(r>q[i].r) change(r,-1),r--;
37 while(l<q[i].l) change(l,-1),l++;
38 q[i].ans=ans;
39 }
40 sort(q+1,q+m+1,cm2);
41 for(int i=1;i<=m;i++) printf("%d\n",q[i].ans);
42 return 0;
43 }