蒟蒻颓废太久不会写平衡树了求助
查看原帖
蒟蒻颓废太久不会写平衡树了求助
639198
Steve_xh楼主2024/12/2 14:00

样例阴差阳错过了。但显然用 output(rt) 输出树发现是错的。

#include<bits/stdc++.h>
using namespace std;
const int MAXN=1e5+5;
int n,m;
mt19937 rnd(random_device{}()*time(nullptr));
struct Treap{
	bool x,tag;
	int l,r,sz,p,v;
}t[MAXN];
int cnt=0,rt=0;
inline int newnode(){
	t[++cnt].x=0;
	t[cnt].tag=t[cnt].l=t[cnt].r=t[cnt].v=0;
	t[cnt].sz=1;
	t[cnt].p=rnd();
	return cnt;
}
void pushup(int x){
	t[x].sz=t[t[x].l].sz+t[t[x].r].sz+1;
	t[x].v=t[t[x].l].v+t[t[x].r].v+t[x].x;
}
void pushdown(int x){
	if(!t[x].tag)
		return ;
	t[x].x=!t[x].x;
	t[x].v=t[x].sz-t[x].v;
	t[t[x].l].tag^=1;
	t[t[x].r].tag^=1;
}
void split(int x,int w,int &l,int &r){
	if(!x)
		return (void)(l=r=0);
	pushdown(x);
	if(t[t[x].l].sz+1<=w)
		l=x,split(t[x].r,w-t[t[x].l].sz-1,t[x].r,r);
	else
		r=x,split(t[x].l,w,l,t[x].l);
	pushup(x);
}
int merge(int l,int r){
	if(!l||!r)
		return l|r;
	if(t[l].p>t[r].p){
		pushdown(l);
		t[l].r=merge(t[l].r,r);
		pushup(l);
		return l;
	}else{
		pushdown(r);
		t[r].l=merge(l,t[r].l);
		pushup(r);
		return r;
	}
}
// void output(int x){
// 	if(!x)
// 		return ;
// 	pushdown(x);
// 	output(t[x].l);
// 	cerr<<"t["<<x<<"]: "<<t[x].x<<", ";
// 	output(t[x].r);
// }
int main(){
	cin.tie(nullptr)->sync_with_stdio(false);
	cin>>n>>m;
	for(int i=1;i<=n;i++)
		rt=merge(rt,newnode());
	for(int i=1,op,x,y,l,p,r;i<=m;i++){
		cin>>op>>x>>y;
		split(rt,y,l,r);
		split(l,x-1,l,p);
		if(op)
			cout<<t[p].v<<'\n';
		else
			t[p].tag^=1;
		rt=merge(merge(l,p),r);
		// cerr<<"now tree{ ";
		// output(rt);
		// cerr<<"};\n";
	}
	return 0;
}


2024/12/2 14:00
加载中...