平衡树

能 pbds 写 pbds

无 pbds 写 fhq

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
const int N=1e5+3;
int rt,tot,lc[N],rc[N],val[N],rd[N],sz[N];
#define ls lc[p]
#define rs rc[p]
void Up(int p){sz[p]=sz[ls]+sz[rs]+1;}
void Spl(int p,int v,int &x,int &y)
{
	if(!p)return x=0,y=0,void();
	if(val[p]<=v)x=p,Spl(rs,v,rs,y);
	else y=p,Spl(ls,v,x,ls);
	Up(p); 
}
int Mer(int x,int y)
{
	if(!x||!y)return x|y;
	if(rd[x]<rd[y])return lc[y]=Mer(x,lc[y]),Up(y),y;
	return rc[x]=Mer(rc[x],y),Up(x),x;
}
int New(int v)
{
	val[++tot]=v;sz[tot]=1;rd[tot]=rand();
	return tot;
}
void Ins(int v)
{
	int x=0,y=0;
	Spl(rt,v-1,x,y);rt=Mer(Mer(x,New(v)),y);
}
void Del(int v)
{
	int x=0,y=0,z=0;
	Spl(rt,v,x,z);Spl(x,v-1,x,y);
	rt=Mer(Mer(x,Mer(lc[y],rc[y])),z);
}
int Rnk(int v)
{
	int x=0,y=0,s=0;
	Spl(rt,v-1,x,y);s=sz[x]+1;
	return rt=Mer(x,y),s;
}
int Kth(int k)
{
	int p=rt;
	while(1)
	{
		if(k==sz[ls]+1)return val[p];
		k<=sz[ls]?p=ls:(k-=sz[ls]+1,p=rs); 
	}
}
int Pre(int v)
{
	int p=rt,s=0;
	while(1)
	{
		if(!p)return s;
		v<=val[p]?p=ls:(s=val[p],p=rs);
	}
}
int Suf(int v)
{
	int p=rt,s=0;
	while(1)
	{
		if(!p)return s;
		v>=val[p]?p=rs:(s=val[p],p=ls);
	}
}
int main()
{
	int T;cin>>T;
	while(T--)
	{
		int op,x;cin>>op>>x;
		if(op==1)Ins(x);
		if(op==2)Del(x);
		if(op==3)cout<<Rnk(x)<<endl;
		if(op==4)cout<<Kth(x)<<endl;
		if(op==5)cout<<Pre(x)<<endl;
		if(op==6)cout<<Suf(x)<<endl; 
	}
}
posted @ 2024-02-01 10:43  Hanghang007  阅读(30)  评论(0)    收藏  举报