Size Balanced Tree模板

#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));
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值