平衡树Splay

文艺平衡树

#include<cstdio>
#include<cstring>
#include<cctype>
#include<algorithm>
#define maxn 100005
using namespace std;

int n,m;
int ch[maxn][2],fa[maxn],siz[maxn],root,tot;
bool rev[maxn];

void dt(int now){
	if(now && rev[now]){
		rev[now]=0;
		swap(ch[now][0],ch[now][1]);
		(ch[now][0]) && (rev[ch[now][0]]^=1);
		(ch[now][1]) && (rev[ch[now][1]]^=1);
	}
}

void up(int now){
	if(now)siz[now]=siz[ch[now][0]]+siz[ch[now][1]]+1;
}

void Rotate(int x){
	if(!fa[x] || !x) return;
	int y=fa[x],z=fa[y];
	dt(x);
	int c=(ch[y][1]==x);
	ch[y][c]=ch[x][!c];
	(ch[y][c]) && (fa[ch[y][c]]=y);
	ch[x][!c]=y;
	fa[y]=x;fa[x]=z;
	if(z) ch[z][ch[z][1]==y]=x;
	up(y),up(x);
}

void build(int &now,int l,int r){
	if(l>r) return;
	int m=(l+r)>>1;
	now=m;
	if(l==r){ up(now);return;}
	build(ch[now][0],l,m-1);(ch[now][0]) && (fa[ch[now][0]]=now);
	build(ch[now][1],m+1,r);(ch[now][1]) && (fa[ch[now][1]]=now);
	up(now);
}

void Splay(int x,int goal){
	dt(x);
	int y,z;
	for(;fa[x]!=goal;Rotate(x)){
		y=fa[x];
		if(y && fa[y]!=goal){
			z=fa[y];
			if((ch[y][1]==x) == (ch[z][1]==y)) Rotate(y);
			else Rotate(x);
		}
	}
	dt(x);if(goal==0)root=x;
	up(x);
}

int Sank(int now,int rk){
	dt(now);
	if(siz[ch[now][0]]+1==rk) return now;
	if(siz[ch[now][0]]+1>rk) return Sank(ch[now][0],rk);
	else return Sank(ch[now][1],rk-siz[ch[now][0]]-1);
}

bool flag=0;
void out(int now){
	if(!now) return ;
	dt(now);
	out(ch[now][0]);
	if(now!=1 && now!=n+2){
		if(!flag) flag=1;
		else printf(" ");
		printf("%d",now-1);
	}
	out(ch[now][1]);
}

int main(){
	int u,v;
	scanf("%d%d",&n,&m);
	build(root,1,n+2);
	for(int i=1;i<=m;i++){
		scanf("%d%d",&u,&v);
		u++,v++;
		Splay(u=Sank(root,u-1),0);
		Splay(v=Sank(root,v+1),root);
		rev[ch[v][0]]^=1;
		dt(ch[v][0]);
	}
	out(root);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值