#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn = 100001;
int key[maxn],chd[maxn][2],siz[maxn],root,top;
int new_node(int e,int s=1){
key[top]=e;
chd[top][0]=chd[top][1]=0;
siz[top]=s;
return top++;
}
void rotate(int &x,bool flag){
int y=chd[x][!flag];
chd[x][!flag]=chd[y][flag];
chd[y][flag]=x;
siz[y]=siz[x];
siz[x]=siz[chd[x][0]]+siz[chd[x][1]]+1;
x=y;
}
void maintain(int &x,bool flag){
if(siz[chd[chd[x][flag]][flag]]>siz[chd[x][!flag]])rotate(x,!flag);
else if(siz[chd[chd[x][flag]][!flag]]>siz[chd[x][!flag]]){rotate(chd[x][flag],flag);rotate(x,!flag);}
else return;
maintain(chd[x][flag],!flag);
maintain(chd[x][!flag],flag);
maintain(x,flag);
maintain(x,!flag);
}
void insert(int &x,int e){
if(!x){x=new_node(e);return;}
siz[x]++;
insert(chd[x][e>=key[x]],e);
maintain(x,e>=key[x]);
}
int remove(int &x,int e){
if(!x)return 0;
siz[x]--;
if(key[x]==e || e<key[x]&&chd[x][0]==0 || e>key[x]&&chd[x][1]==0){
int y=key[x];
if(!chd[x][0]||!chd[x][1])x=chd[x][0]+chd[x][1];
else key[x]=remove(chd[x][0],e+1);
return y;
}else remove(chd[x][e>=key[x]],e);
}
int pre(int x,int y,int e){
if(!x)return y;
if(e<key[x])return pre(chd[x][0],y,e);
else return pre(chd[x][1],x,e);
}
int next(int x,int y,int e){
if(!x)return y;
if(e<=key[x])return next(chd[x][0],x,e);
else return next(chd[x][1],y,e);
}
int find_kth(int x,int k){
if(k<=siz[chd[x][0]])return find_kth(chd[x][0],k);
else if(k==siz[chd[x][0]]+1)return key[x];
else return find_kth(chd[x][1],k-siz[chd[x][0]]-1);
}
int main(){
int t,x;
top=1;
while(~scanf("%d",&t)){
if(t==1){
scanf("%d",&x);
insert(root,x);
}else if(t==2){
scanf("%d",&x);
remove(root,x);
}else if(t==3){
scanf("%d",&x);
printf("%d %d\n",key[pre(root,0,x)],key[next(root,0,x)]);
}else if(t==4){
scanf("%d",&x);
printf("%d\n",find_kth(root,x));
}
}
}
Size Balanced Tree模板
最新推荐文章于 2023-12-28 19:55:11 发布