跳到正文

题解

题解:CF1477B Nezzar and Binary String

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

文章信息

发布
2026年7月15日
收录
2026年7月17日
更新
2026年11月11日
篇幅
约 4 分钟

版本

  1. v1当前

拿到题发现一点思路都没有,正难则反。

思路

正常人肯定是先修改再检查,所以考虑倒着来。

然后就可以发现每次决策是一定的,只需要统计区间 0 和 1 的数量和区间赋值,上个线段树就解决了。

代码

上个代码。

C++
#include<bits/stdc++.h>
using namespace std;
#define ls (x<<1)
#define rs (x<<1|1)
#define mid ((L+R)>>1)
const int N=2e5+5;
struct Tree{
	int val,lz;
}tr[N*4];
int n,q,l[N],r[N];
string s,f;
void push_up(int x) {tr[x].val=tr[ls].val+tr[rs].val;}
void build(int x,int L,int R){
	tr[x].lz=tr[x].val=0;
	if(L==R) return tr[x].val=(f[L]=='0'?1:0),void();
	build(ls,L,mid),build(rs,mid+1,R);
	push_up(x);
}
void lazy(int x,int L,int R,int op){
	if(op==-1) tr[x].val=0,tr[x].lz=-1;
	if(op==1) tr[x].val=(R-L+1),tr[x].lz=1;
}
void push_down(int x,int L,int R){
	lazy(ls,L,mid,tr[x].lz),lazy(rs,mid+1,R,tr[x].lz);
	tr[x].lz=0;
}
void update(int x,int L,int R,int l,int r,int op){
	if(l<=L&&R<=r) return lazy(x,L,R,op),void();
	if(tr[x].lz) push_down(x,L,R);
	if(l<=mid) update(ls,L,mid,l,r,op);
	if(r>mid) update(rs,mid+1,R,l,r,op);
	push_up(x);
}
int query(int x,int L,int R,int l,int r){
	if(l<=L&&R<=r) return tr[x].val;
	if(tr[x].lz) push_down(x,L,R);
	int ans=0;
	if(l<=mid) ans=query(ls,L,mid,l,r);
	if(r>mid) ans+=query(rs,mid+1,R,l,r);
	return ans;
}
void work(){
	cin>>n>>q;
	cin>>s>>f;s=" "+s,f=" "+f;
	build(1,1,n);
	for(int i=1;i<=q;i++) cin>>l[i]>>r[i];
	for(int i=q;i>=1;i--){
		int w=query(1,1,n,l[i],r[i]);
//		cout<<w<<" "<<r[i]-l[i]+1<<"\n";
		if(w*2==r[i]-l[i]+1) return cout<<"NO\n",void();
		if(w*2<r[i]-l[i]+1) update(1,1,n,l[i],r[i],-1);
		else update(1,1,n,l[i],r[i],1);
	}
	for(int i=1;i<=n;i++){
		int w=query(1,1,n,i,i),l=(s[i]=='0'?1:0);
		if(l!=w) return cout<<"NO\n",void();
	}
	cout<<"YES\n";
}
signed main(){
	ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
	int t;
	cin>>t;
//	cout<<"\n\n\n\n";
	while(t--) work();
}
原文