平衡树

普通平衡树

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N=1e5+10;
ll root,tot;
struct node{ll ls,rs,val,pri,sz;}t[N];
void pushup(ll u){
	t[u].sz=t[t[u].ls].sz+t[t[u].rs].sz+1;
}
void spl(ll u,ll x,ll &L,ll &R){
	if(u==0){L=R=0;return;}
	if(t[u].val<=x)L=u,spl(t[u].rs,x,t[u].rs,R);
	else R=u,spl(t[u].ls,x,L,t[u].ls);
	pushup(u);
}
ll mrg(ll L,ll R){
	if(L==0||R==0)return L+R;
	if(t[L].pri>t[R].pri){t[L].rs=mrg(t[L].rs,R),pushup(L);return L;}
	else {t[R].ls=mrg(L,t[R].ls),pushup(R);return R;}
}
void isr(ll x){
	ll L,R;
	spl(root,x,L,R);
	t[++tot]=(node){0,0,x,rand(),1};
	root=mrg(mrg(L,tot),R);
}
void del(ll x){
	ll L,R,p;
	spl(root,x,L,R);
	spl(L,x-1,L,p);
	p=mrg(t[p].ls,t[p].rs);
	root=mrg(mrg(L,p),R);
}
void rk(ll x){
	ll L,R;
	spl(root,x-1,L,R);
	cout << t[L].sz+1 << endl;
	root=mrg(L,R);
}
ll kth(ll u,ll k){
	if(k<=t[t[u].ls].sz)return kth(t[u].ls,k);
	else if(k>t[t[u].ls].sz+1)return kth(t[u].rs,k-t[t[u].ls].sz-1);
	else return u;
}
void prec(ll x){
	ll L,R;
	spl(root,x-1,L,R);
	cout << t[kth(L,t[L].sz)].val << endl;
	root=mrg(L,R);
}
void sufc(ll x){
	ll L,R;
	spl(root,x,L,R);
	cout << t[kth(R,1)].val << endl;
	root=mrg(L,R);
}
int main(){
	int n;
	cin >> n;
	while(n--){
		ll op,x;
		cin >> op >> x;
		if(op==1)isr(x);
		else if(op==2)del(x);
		else if(op==3)rk(x);
		else if(op==4)cout << t[kth(root,x)].val << endl;
		else if(op==5)prec(x);
		else if(op==6)sufc(x);
	}
	return 0;
}
posted @ 2024-01-06 14:44  Alric  阅读(2)  评论(0编辑  收藏  举报