- 题意
给你一个区间,每次查询(l,r),问(l,r)中数字出现偶数次的种类数。
- 题解
分块大法好。。。
分析:
1.查询(l,r)中的数字出现偶数次的种类数,可以等价于完整块中数字种类数及不完整块中数字种类数(前半部分可以预处理,后半部分暴力)时间复杂度
O(n√)
2.对于不完整块种类数,要考虑与完整块中数字出现重复,这时我们需要求出完整块中某个数的个数,再来统计影响。
3.对于求完整块中数字出现重复,看了其他人的博客,大部分用到了排序并二分查找,时间复杂度
O(n√⋅logn)
。这里给出一种牺牲空间复杂度换取时间复杂度的方法:
预处理第一块到每一块的每个数出现的次数,时间复杂度
O(n√⋅n)
,空间复杂度
O(n√⋅n)
,那么查询只需要
O(1)
,跑下来明显比前一种方法更为优秀。(当然这时候空间可能会爆,所以要适当调整块的大小。。)
- Code
#include<bits/stdc++.h>
using namespace std;
const int Maxn=1e5+50;
const int S=430;
inline int read()
{
char ch=getchar();int i=0,f=1;
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch)){i=(i<<1)+(i<<3)+ch-'0';ch=getchar();}
return i*f;
}
int n,m,c,t,a[Maxn],ans[250][250],cnt[250][Maxn],C[Maxn],bg[Maxn],ed[Maxn],s;
struct node
{
int val,id;
friend inline bool operator <(const node &a,const node &b){return a.val<b.val;}
}b[Maxn];
inline void l_b()
{
sort(b+1,b+n+1);
t=0;
for(int i=1;i<=n;i++)
{
if(i==1||b[i].val!=b[i-1].val)++t;
a[b[i].id]=t;
}
}
inline void pre()
{
for(int i=1;i*S<=n;i++){bg[i]=ed[i-1]+1,ed[i]=ed[i-1]+S,s=i;}
if(ed[s]!=n)++s,bg[s]=ed[s-1]+1,ed[s]=n;
int h=1;
for(int i=1;i<=n;i++)
{
C[a[i]]++;
if(i==ed[h])
{
for(int i=1;i<=t;i++)cnt[h][i]=C[i];
++h;
}
}
memset(C,0,sizeof(C));
for(int i=1;i<=s;i++)
{
int tot=0;h=i;
for(int j=bg[i];j<=n;j++)
{
++C[a[j]];
if(C[a[j]]!=1)
{
if(C[a[j]]%2)--tot;
else ++tot;
}
if(j==ed[h])
{
ans[i][h]=tot;
h++;
}
}
for(int j=bg[i];j<=n;j++)
{
--C[a[j]];
}
}
}
int buf[50];
inline void W(int x)
{
if(!x)putchar('0');
if(x<0)putchar('-'),x=-x;
while(x)buf[++buf[0]]=(x%10),x/=10;
while(buf[0])putchar('0'+buf[buf[0]--]);
}
int main()
{
n=read(),c=read(),m=read();
for(int i=1;i<=n;i++){b[i].val=read(),b[i].id=i;}
l_b();
pre();
int A=0;
memset(C,0,sizeof(C));
while(m--)
{
int l=(read()+A)%n+1,r=(read()+A)%n+1;
if(l>r)swap(l,r);
if((r-l+1)>2*S)
{
int L=(l-1)/S+1,R=(r-1)/S+1;
if(l!=bg[L])L++;
if(r!=ed[R])R--;
int tot=ans[L][R];
for(int i=l;i<bg[L];i++)
{
C[a[i]]++;
if((C[a[i]]+cnt[R][a[i]]-cnt[L-1][a[i]])!=1)
{
if((C[a[i]]+cnt[R][a[i]]-cnt[L-1][a[i]])%2)--tot;
else ++tot;
}
}
for(int i=ed[R]+1;i<=r;i++)
{
C[a[i]]++;
if((C[a[i]]+cnt[R][a[i]]-cnt[L-1][a[i]])!=1)
{
if((C[a[i]]+cnt[R][a[i]]-cnt[L-1][a[i]])%2)--tot;
else ++tot;
}
}
A=tot;
for(int i=l;i<bg[L];i++){--C[a[i]];}
for(int i=ed[R]+1;i<=r;i++){--C[a[i]];}
}
else
{
int tot=0;
for(int i=l;i<=r;i++)
{
++C[a[i]];
if(C[a[i]]!=1)
{
if(C[a[i]]%2)--tot;
else ++tot;
}
}
A=tot;
for(int i=l;i<=r;i++){--C[a[i]];}
}
W(A);
putchar('\n');
}
}