题目:
题目链接:[LUOGU XOR的艺术]
双倍经验:[USACO08NOV 光开关Light Switching]
三倍经验:[LUOGU [TJOI2009] 开关]
题解:
异或操作,区间和即可。
代码:
#include<bits/stdc++.h>
using namespace std;
inline int read()
{
int s=0,w=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch<='9'&&ch>='0')s=s*10+ch-'0',ch=getchar();
return s*w;
}
const int sea=2e6+7;
struct hit{int w;}tr[sea*4];
char ch[sea];
int n,m,s,x,y,ans,a[sea],lazy[sea];
void build(int l,int r,int k)
{
if(l==r){tr[k].w=a[l]; return;}
int mid=(l+r)>>1;
build(l,mid,k<<1); build(mid+1,r,k<<1|1);
tr[k].w=tr[k<<1].w+tr[k<<1|1].w;
}
void down(int k,int len)
{
if(!lazy[k]) return ;
lazy[k<<1]^=1; lazy[k<<1|1]^=1;
tr[k<<1].w=(len-(len>>1))-tr[k<<1].w;
tr[k<<1|1].w=(len>>1)-tr[k<<1|1].w;
lazy[k]=0;
}
int ask(int l,int r,int k)
{
if(l>=x&&r<=y)return tr[k].w;
down(k,r-l+1);
int mid=(r+l)>>1; int ans=0;
if(x<=mid) ans+=ask(l,mid,k<<1);
if(mid+1<=y) ans+=ask(mid+1,r,k<<1|1);
return ans;
}
void alter(int l,int r,int k)
{
down(k,r-l+1);
if(l>=x&&r<=y){lazy[k]^=1;tr[k].w=r-l+1-tr[k].w; return ;}
int mid=(l+r)>>1;
if(x<=mid) alter(l,mid,k<<1); if(y>mid) alter(mid+1,r,k<<1|1);
tr[k].w=tr[k*2].w+tr[k*2+1].w;
}
int main()
{
n=read(),m=read();
for(int i=1;i<=n;i++) cin>>ch[i];
for(int i=1;i<=n;i++) a[i]=ch[i]-'0';
build(1,n,1);
for(int i=1;i<=m;i++)
{
s=read(),x=read(),y=read();
if(s==0) alter(1,n,1);
if(s==1) printf("%d\n",ask(1,n,1));
}
return 0;
}