跳到正文

个人记录

线段树-结构体封装

smalbug约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年6月18日
更新
2026年6月18日
篇幅
约 4 分钟

版本

  1. v1当前

P2574 XOR的艺术

C++
#include<bits/stdc++.h>
#define lc x<<1 
#define rc x<<1|1
#define N ((int)2e5+5) 
using namespace std;
int n,q;
int a[N];
struct Msg{
	int s;
	Msg():s(0){}
	Msg(int _s):s(_s){}
	Msg operator + (const Msg &_t){
		return Msg(s+_t.s);
	}
};
struct Tag{
	int k;
	Tag():k(0){}
	Tag(int _k):k(_k){}
	operator bool ()const{
		return k;
	}
	Tag operator + (const Tag &_t)const{
		return Tag(k^_t.k);
	}
	Msg apply(const Msg &_t,int l,int r)const{
		int _s=r-l+1-_t.s;
		return Msg(_s);
	}
};
Msg msg[N<<2];
Tag tag[N<<2];
void pushup(int x){
	msg[x]=msg[lc]+msg[rc];
	return ;
}
void apply(int x,int l,int r,Tag t){
	tag[x]=tag[x]+t;
	msg[x]=t.apply(msg[x],l,r);
	return ;
}
void pushdown(int x,int l,int r){
	if(!tag[x])return ;
	int mid=(l+r)>>1;
	apply(lc,l,mid,tag[x]);
	apply(rc,mid+1,r,tag[x]);
	tag[x]=Tag();
	return ;
}
void build(int x,int l,int r){
	msg[x]=Msg();
	tag[x]=Tag();
	if(l==r){
		msg[x]=Msg(a[l]);
		return;
	}
	int mid=(l+r)>>1;
	build(lc,l,mid);
	build(rc,mid+1,r);
	pushup(x);
	return ;
}
void modify(int x,int l,int r,int L,int R,Tag t){
	if(L<=l&&r<=R){
		apply(x,l,r,t);
		return ;
	}
	pushdown(x,l,r);
	int mid=(l+r)>>1;
	if(L<=mid)modify(lc,l,mid,L,R,t);
	if(R>mid)modify(rc,mid+1,r,L,R,t);
	pushup(x);
	return ;
}
Msg query(int x,int l,int r,int L,int R){
	if(L<=l&&r<=R){
		return msg[x];
	}
	pushdown(x,l,r);
	int mid=(l+r)>>1;
	Msg ret=Msg();
	if(L<=mid)ret=ret+query(lc,l,mid,L,R);
	if(R>mid)ret=ret+query(rc,mid+1,r,L,R);
	return ret;
}

int main(){
	cin>>n>>q;
	for(int i=1;i<=n;i++){
		char x;
		cin>>x;
		a[i]=x-'0';
	}
	build(1,1,n);
	while(q--){
		int op,x,y;
		cin>>op>>x>>y;
		if(op){
			cout<<query(1,1,n,x,y).s<<'\n';
		}else{
			modify(1,1,n,x,y,Tag(1));
		}
	}
	return 0;
} 
原文