求调Splay
查看原帖
求调Splay
548999
As_Snow楼主2022/11/17 09:23
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+15;
const int inf = 1e9+7;
struct node{
	int val,cnt,size;
	int fa,son[2];
}tr[N];
#define ls son[0]
#define rs son[1]
int Size,root;
void pushup(node &U){U.size=tr[U.son[0]].size+tr[U.son[0]].size+U.cnt;}
bool get(int &u){return u==tr[tr[u].fa].son[1];}
void erase(node &U){U=(node){0,0,0,0,{0,0}};}
void rotate(int u){
	int fa=tr[u].fa,gf=tr[fa].fa;
	bool chk=get(u);
	tr[fa].son[chk]=tr[u].son[chk^1];
	if(tr[fa].son[chk^1])
		tr[tr[fa].son[chk^1]].fa=fa;
	tr[u].son[chk^1]=fa;
	if(gf)tr[gf].son[get(fa)]=u;
	tr[fa].fa=u,tr[u].fa=gf;
	pushup(tr[fa]),pushup(tr[u]);
}
void splay(int u){
	for(int fa=tr[u].fa;(fa=tr[u].fa);rotate(u)){
		if(tr[fa].fa){
			rotate((get(u)==get(fa))?fa:u);
		}
	}
	root=u;
}
int newnode(int &key,int fa=0){
	tr[++Size]={key,1,1,fa,{0,0}};
	tr[fa].son[tr[fa].val<key]=Size;
	pushup(tr[fa]);
	return Size;
}
void insert(int &key){
	int u=root,fa=0;
	if(root==0)return void(root=newnode(key));
	while(1){
		if(tr[u].val==key){
			tr[u].cnt++;
			pushup(tr[u]),pushup(tr[fa]);
			splay(u);	
			return;
		}
		fa=u,u=tr[fa].son[tr[fa].val<key];
		if(u==0){
			newnode(key,fa);
			return;
		}
	}
}
int ranking(const int &key){
	int res=0,u=root;
	while(1){
		if(key<tr[u].val)
			u=tr[u].son[0];
		else{
			res+=tr[tr[u].son[0]].size;
			if(key==tr[u].val)
				return splay(u),res+1;
			res+=tr[u].cnt,u=tr[u].son[1];
		}
	}
	return 0;
}
int keyth(int rank){
	int u=root;
	if(rank<=tr[tr[u].son[0]].size)u=tr[u].son[0];
	else{
		rank-=tr[tr[u].son[0]].size+tr[u].cnt;
		if(rank<=0)return splay(u),tr[u].val;
		u=tr[u].son[1];
	}
	return 0;
}
int prev(){
	int u=tr[root].son[0];
	if(!u)return u;
	while(tr[u].son[1])u=tr[u].son[1];
	splay(u);
	return u;
}
int next(){
	int u=tr[root].son[1];
	if(!u)return u;
	while(tr[u].son[0])u=tr[u].son[0];
	splay(u);
	return u;
}
void remove(int key){
	ranking(key);
	tr[root].cnt--;
	if(tr[root].cnt)return pushup(tr[root]);
	int u=root;
	if(!tr[root].son[0]&&!tr[root].son[1]){
		erase(tr[root]),root=0;
		return;
	}
	if(!tr[root].son[0]){
		root=tr[u].son[1],tr[root].fa=0;
		erase(tr[u]);
		return;
	}
	if(!tr[root].son[1]){
		root=tr[u].son[0],tr[root].fa=0;
		erase(tr[u]);
		return;
	}
	prev();
	tr[tr[u].son[1]].fa=root;
	tr[root].son[1]=tr[u].son[1];
	erase(tr[u]),pushup(tr[root]);
}
int n,op,x;
signed main(){
	scanf("%d",&n);
	while(n--){
		scanf("%d%d",&op,&x);
		if(op==1)insert(x);
		else if(op==2)remove(op);
		else if(op==3)printf("%d\n",ranking(x));
		else if(op==4)printf("%d\n",keyth(x));
		else if(op==5){
			insert(x),printf("%d\n",tr[prev()].val),remove(x);
		}
		else if(op==6){
			insert(x),printf("%d\n",tr[next()].val),remove(x);
		}
	}
	return 0;
}
2022/11/17 09:23
加载中...