lqs code

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,cnt,l,r,root;
struct node{
	int val,siz,ls,rs,f;
	bool tag;
}a[200005];
int newnode(int val){
	a[++cnt].val=val;
	a[cnt].siz=1;
	return cnt;
}
void update(int x){
	a[x].siz=1;
	if(a[x].ls)a[x].siz+=a[a[x].ls].siz;
	if(a[x].rs)a[x].siz+=a[a[x].rs].siz;
}
int build(int l,int r){
	if(l>r)return 0;
	int m=(l+r)/2,p=newnode(m);
	a[p].ls=build(l,m-1);
	a[p].rs=build(m+1,r);
	update(p);
	if(a[p].ls)a[a[p].ls].f=p;
	if(a[p].rs)a[a[p].rs].f=p;
	return p;
}
void pushdown(int x){
	if(a[x].tag){
		a[x].tag=0;
		swap(a[x].ls,a[x].rs);
		if(a[x].ls)a[a[x].ls].tag^=1;
		if(a[x].rs)a[a[x].rs].tag^=1;
	}
}
void zig(int x){
	int y=a[x].f,z=a[y].f;
	a[y].ls=a[x].rs;
	if(a[x].rs)a[a[x].rs].f=y;
	update(y);
	a[x].rs=y;
	a[y].f=x;
	update(x);
	a[x].f=z;
	if(z){
		if(a[z].ls==y)a[z].ls=x;
		else a[z].rs=x;
		update(z);
	}
}
void zag(int x){
	int y=a[x].f,z=a[y].f;
	a[y].rs=a[x].ls;
	if(a[x].ls)a[a[x].ls].f=y;
	update(y);
	a[x].ls=y;
	a[y].f=x;
	update(x);
	a[x].f=z;
	if(z){
		if(a[z].ls==y)a[z].ls=x;
		else a[z].rs=x;
		update(z);
	}
}
void splay(int x,int g){
	while(a[x].f!=g){
		int y=a[x].f,z=a[y].f;
		if(z)pushdown(z);
		pushdown(y);
		if(z==g){
			if(x==a[y].ls)zig(x);
			else zag(x);
			continue;
		}
		bool p1=x==a[y].ls,p2=y==a[z].ls;
		if(p1&&p2)zig(y),zig(x);
		else if(p1&&!p2)zig(x),zag(x);
		else if(!p1&&p2)zag(x),zig(x);
		else zag(y),zag(x);
	}
	if(!g)root=x;
}
int find(int x,int rnk){
	pushdown(x);
	int lsize=0;
	if(a[x].ls)lsize=a[a[x].ls].siz;
	if(rnk<=lsize)return find(a[x].ls,rnk);
	if(rnk<=lsize+1)return x;
	return find(a[x].rs,rnk-lsize-1);
}
void reverse(){
	int p=find(root,l),q=find(root,r+2);
	splay(p,0),splay(q,p);
	if(a[q].ls)a[a[q].ls].tag^=1;
}
void print(int x){
	pushdown(x);
	if(a[x].ls)print(a[x].ls);
	if(a[x].val>=1&&a[x].val<=n)cout<<a[x].val<<' ';
	if(a[x].rs)print(a[x].rs);
}
signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m;
	root=build(0,n+1);
	while(m--){
		cin>>l>>r;
		reverse();
	}
	print(root);
}
posted @ 2025-05-10 16:16  TallBanana  阅读(45)  评论(0)    收藏  举报