Splay求助44pts
查看原帖
Splay求助44pts
701478
_FastFT2013楼主2024/4/5 18:17

第5,6,7,8,9,10,11,12的点T掉了

#include<iostream>
using namespace std;
const int N=1e5+5;
struct Splay{
	int rt=0,tot=0;
	int fa[N]={0};
	int ch[N][2]={0};
	int val[N]={0};
	int cnt[N]={0};
	int sz[N]={0};
	void gx(int x){
		sz[x]=sz[ch[x][0]]+sz[ch[x][1]]+cnt[x];
	}
	bool get(int x){
		return x==ch[fa[x]][1];
	}
	void clear(int x){
		ch[x][0]=ch[x][1]=fa[x]=val[x]=cnt[x]=sz[x]=0;
	}
	void rotate(int x){
		int y=fa[x],z=fa[y],d=get(x);
		ch[y][d]=ch[x][d^1];
		if(ch[x][d^1])fa[ch[x][d^1]]=y;
		ch[x][d^1]=y;
		fa[y]=x;
		fa[x]=z;
		if(z)ch[z][y==ch[z][1]]=x;
		gx(y);
		gx(x);
	}
	void splay(int x){
		for(int f=fa[x];f=fa[x],f;rotate(x)){
			if(fa[f])rotate(get(f)==get(x)?f:x);
		}
		rt=x;
	}
	void ins(int k){
		if(!rt){
			val[++tot]=k;
			cnt[tot]++;
			rt=tot;
			gx(rt);
			return;
		}
		int cur=rt,f=0;
		while(true){
			if(val[cur]==k){
				cnt[cur]++;
				gx(cur);
				gx(f);
				splay(cur);
				return;
			}
			f=cur;
			cur=ch[cur][val[cur]<k];
			if(!cur){
				val[++tot]=k;
				cnt[tot]++;
				fa[tot]=f;
				if(f!=0)ch[f][val[f]<k]=tot;
				gx(tot);
				gx(f);
				splay(tot);
				return;
			}
		}
	}
	int rk(int x){
		int ans=0,cur=rt;
		while(true&&cur){
			if(x<val[cur]){
				cur=ch[cur][0];
			}else{
				ans+=sz[ch[cur][0]];
				if(x==val[cur]){
					splay(cur);
					return ans+1;
				} 
				ans+=cnt[cur];
				cur=ch[cur][1];
			}
		}
		return ans+1;
	} 
	int kth(int k){
		int cur=rt;
		while(true&&cur){
			if(ch[cur][0]&&k<=ch[cur][0]){
				cur=ch[cur][0];
			}else{
				k-=cnt[cur]+sz[ch[cur][0]];
				if(k<=0){
					splay(cur);
					return val[cur];
				}
				cur=ch[cur][1];
			}
		}
		return 0;
	}
	int pre(){
		int cur=ch[rt][0];
		if(!cur)return cur;
		while(ch[cur][1])cur=ch[cur][1];
		splay(cur);
		return cur;
	}
	int nxt(){
		int cur=ch[rt][1];
		if(!cur)return cur;
		while(ch[cur][0])cur=ch[cur][0];
		splay(cur);
		return cur;		
	}
	void del(int x){
		rk(x);
		if(cnt[rt]>1){
			cnt[rt]--;
			gx(rt);
			return;
		}
		if(!ch[rt][0]&&!ch[rt][1]){
			clear(rt);
			rt=0;
			return;
		}
		if(!ch[rt][0]){
			int cur=rt;
			rt=ch[rt][1];
			fa[rt]=0;
			clear(cur);
			return;
		}
		if(!ch[rt][1]){
			int cur=rt;
			rt=ch[rt][0];
			fa[rt]=0;
			clear(cur);
			return;
		}
		int cur=rt,p=pre();
		fa[ch[cur][1]]=p;
		ch[p][1]=ch[cur][1];
		clear(cur);
		gx(rt);
	}
	void zxbl(int x){
		if(!x)return;
		zxbl(ch[x][0]);
		cout<<val[x]<<" ";
		zxbl(ch[x][1]);
	}
};
Splay a;
int main(){
	int t;
	cin>>t;
	while(t--){
		int op;
		cin>>op;
		if(op==1){
			int x;
			cin>>x;
			a.ins(x);
		}else if(op==2){
			int x;
			cin>>x;
			a.del(x);
		}else if(op==3){
			int x;
			cin>>x;
			cout<<a.rk(x)<<"\n";
		}else if(op==4){
			int x;
			cin>>x;
			cout<<a.kth(x)<<"\n";
		}else if(op==5){
			int x;
			cin>>x;
			a.ins(x);
			cout<<a.val[a.pre()]<<"\n";
			a.del(x);
		}else{
			int x;
			cin>>x;
			a.ins(x);
			cout<<a.val[a.nxt()]<<"\n";
			a.del(x);	
		}
	}
	return 0;
} 
2024/4/5 18:17
加载中...