萌新splay WA+RE 44pts求助 悬赏1关注
查看原帖
萌新splay WA+RE 44pts求助 悬赏1关注
743811
Shakespeare07楼主2022/11/4 10:42
#include<bits/stdc++.h>
using namespace std;

#define il inline
#define re register
#define int long long

il int read(){
	int s=0,w=1;char c=getchar();
	while(!isdigit(c)){ if(c=='-') w=-1;c=getchar();}
	while(isdigit(c)){ s=(s<<3)+(s<<1)+(c^48);c=getchar();}
	return s*w;
}
il void write(re int x){
	if(x<0){
		x=-x;
		putchar('-');
	}
	if(x>9) write(x/10);
	putchar((char)(x%10+48));
}

const int N=1e5+5;

int tot,rt;
struct Splay{
	int val,sz,cnt,ch[2],fa;
}tr[N];

il void pu(re int x){
	tr[x].sz=tr[tr[x].ch[0]].sz+tr[tr[x].ch[1]].sz+1;
}

il void rotate(re int x){
	int y=tr[x].fa;
	int z=tr[y].fa;
	int k=(tr[y].ch[1]==x);
	tr[z].ch[tr[z].ch[1]==y]=x;
	tr[x].fa=z;
	tr[y].ch[k]=tr[x].ch[k^1];
	tr[tr[x].ch[k^1]].fa=y;
	tr[x].ch[k^1]=y;
	tr[y].fa=x;
	pu(y),pu(x);
}

il void splay(re int x,re int goal){
	while(tr[x].fa!=goal){
		int y=tr[x].fa;
		int z=tr[y].fa;
		if(z!=goal){
			((tr[z].ch[1]==y)^(tr[y].ch[1]==x))?rotate(x):rotate(y);
		}
		rotate(x);
	}
	if(!goal) rt=x;
}

il void find(re int x){
	int u=rt;
	if(!u) return;
	while(tr[u].ch[x>tr[u].val] && tr[u].val!=x)
		u=tr[u].ch[x>tr[u].val];
	splay(u,0);
}

il int Next(re int x,re int f){
	find(x);
	int u=rt;
	if(!f && tr[u].val<x) return u;
	if(f && tr[u].val>x) return u;
	u=tr[u].ch[f];
	while(tr[u].ch[f^1]) u=tr[u].ch[f^1];
	return u; 
}

il void ins(re int x){
	int u=rt,fa=0;
	while(u && tr[u].val!=x) fa=u,u=tr[u].ch[x>tr[u].val];
	if(tr[u].cnt) ++tr[u].cnt;
	else{
		u=++tot;
		if(fa) tr[fa].ch[x>tr[fa].val]=u;
		tr[u].fa=fa;
		tr[u].ch[0]=tr[u].ch[1]=0;
		tr[u].sz=tr[u].cnt=1;
		tr[u].val=x;
	}
	splay(u,0);
}

il void del(re int x){
	int pre=Next(x,0);
	int nxt=Next(x,1);
	splay(nxt,0);
	splay(pre,nxt);
	
	int u=tr[pre].ch[1];
	
	if(tr[u].cnt>1){
		--tr[u].cnt;
		splay(u,0);
	}
	else tr[pre].ch[1]=0;
}

il int kth(re int k){
	int u=rt;
	if(k>tr[u].sz) return (int)(1e15);
	while(true){
		if(k<=tr[tr[u].ch[0]].sz) u=tr[u].ch[0];
		else if(k>tr[tr[u].ch[0]].sz && k<=tr[tr[u].ch[0]].sz+tr[u].cnt) return u;
		else k-=tr[tr[u].ch[0]].sz+tr[u].cnt,u=tr[u].ch[1];
	}
}

signed main(){
	int T=read();
	
	ins((int)(-2e9));
	ins((int)(2e9));
	
	while(T--){
		int opt=read(),x=read();
		if(opt==1) ins(x);
		else if(opt==2) del(x);
		else if(opt==3){
			find(x);
			write(tr[tr[rt].ch[0]].sz),putchar('\n');
		}
		else if(opt==4){
			write(tr[kth(x+1)].val),putchar('\n');
		}
		else if(opt==5){
			write(tr[Next(x,0)].val),putchar('\n');
		}
		else{
			write(tr[Next(x,1)].val),putchar('\n');
		}
	}
	
	return 0;
}
2022/11/4 10:42
加载中...