《还是Splay》
  • 板块学术版
  • 楼主optimize_2
  • 当前回复6
  • 已保存回复6
  • 发布时间2020/7/28 13:32
  • 上次更新2023/11/6 21:59:28
查看原帖
《还是Splay》
224978
optimize_2楼主2020/7/28 13:32

print操作一直死循环,应该是树的结构错了

#include<bits/stdc++.h>
using namespace std;

struct SplayNode {
	int f;
	int val;
	int size;
	int son[2];
	
	bool tag;
	
	#define fa(x) t[x].f
	#define val(x) t[x].val
	#define size(x) t[x].size
	#define tag(x) t[x].tag
	#define ls(x) t[x].son[0]
	#define rs(x) t[x].son[1]
}t[10010];
int rt,tot;

int n,m,a[100010];
int x,y;

int whichSon(int x) {return x==rs(fa(x));}

void update(int x) {
	if(!x) return;
	size(x)=1;
	if(ls(x)) size(x)+=size(ls(x));
	if(rs(x)) size(x)+=size(rs(x));
}

void push_down(int x) {
	if(x&&tag(x)) {
		tag(ls(x))^=1;
		tag(rs(x))^=1;
		swap(ls(x),rs(x));
		tag(x)=0;
	}
}
/*
void rotate(int x) {
	int s=whichSon(x);
	int of=fa(x);
	int s2=whichSon(of);
	int gf=fa(of);
	push_down(of);
	push_down(gf);
	if(t[x].son[s^1]) {
		t[of].son[s]=t[x].son[s^1];
		fa(t[of].son[s])=of;
	}
	fa(of)=x;
	fa(x)=gf;
	t[x].son[s^1]=of;
	if(gf) t[gf].son[s2]=x;
	update(of);
}
*/
/*
inline void rotate(int x){
	int fnow=t[x].f,ffnow=t[fnow].f;
	push_down(x),push_down(fnow);
	bool w=whichSon(x);
	t[fnow].son[w]=t[x].son[w^1];
	t[t[fnow].son[w]].f=fnow;
	t[fnow].f=x;
	t[x].f=ffnow;
	t[x].son[w^1]=fnow;
	if(ffnow){
		t[ffnow].son[t[ffnow].son[1]==fnow]=x;
	}
	update(fnow);
}
*/

inline void rotate(int x){
	int of=fa(x);
	int gf=fa(of);
	push_down(x),push_down(of);
	bool s=whichSon(x);
	bool s2=whichSon(of);
	t[of].son[s]=t[x].son[s^1];
	fa(t[of].son[s])=of;
	fa(of)=x;
	fa(x)=gf;
	t[x].son[s^1]=of;
	if(gf){
		t[gf].son[s2]=x;
	}
	update(of);
}

void splay(int x,int goal) {
	for(int f;(f=fa(x))!=goal;rotate(x))
		if(fa(f)!=goal) {
			/*
			if(whichSon(x)==whichSon(f)) rotate(f);
			else rotate(x);
			*/
			cout<<x<<" "<<f<<endl;
			rotate(whichSon(x)==whichSon(f)?f:x);
		}
			
	if(goal==0) rt=x;
}

int findKth(int x) {
	int now=rt;
	while(1) {
		//cout<<x<<" "<<size(ls(x))<<" "<<size(rs(x))<<endl;
		push_down(now);
		if(size(ls(now))>=x) now=ls(x);
		else {
			x-=size(ls(now))+1;
			if(x==0) return now;
			else now=rs(x);
		}
	}
}

void reverse(int x,int y) {
	int l=findKth(x-1),r=findKth(y+1);
	splay(l,0);
	splay(r,l);
	int pos=ls(rs(rt));
	tag(pos)^=1;
}

void print(int now) {
	cout<<now<<" "<<ls(now)<<" "<<rs(now)<<endl;
	push_down(now);
	if(ls(now)) print(ls(now));
	if(val(now)!=-2147483647&&val(now)!=2147483647){
		cout<<val(now)<<" ";
	}
	if(rs(now)) print(rs(now));
}

int build(int l,int r,int f) {
	if(l>r) return 0;
	int mid=(l+r)>>1;
	tot++;
	fa(tot)=f;
	ls(tot)=0;
	rs(tot)=0;
	val(tot)=a[mid];
	size(tot)=1;
	ls(tot)=build(l,mid-1,tot);
	rs(tot)=build(mid+1,r,tot);
	update(tot);
	return tot;
}

int main() {
	cin>>n>>m;
	a[1]=-2147483647;
	a[n+2]=2147483647;
	for(int i=2;i<=n+1;i++) {
		a[i]=i-1;
	}
	
	rt=build(1,n+2,0);
	//reverse(2,5);
	
	for(int i=1;i<=m;i++) {
		cin>>x>>y;
		reverse(x+1,y+1);
		print(rt);
	}
	print(rt);
	
}
2020/7/28 13:32
加载中...