#include<cstdio>
#include<iostream>
using namespace std;
const int N=1e5+5;
int ch[N][2],f[N],sz[N],cnt[N],val[N];
int tot,root;
inline void _clear(int x){
ch[x][0]=ch[x][1]=f[x]=sz[x]=cnt[x]=val[x]=0;
}
inline void update(int x){
if(!x) return;
sz[x]=cnt[x];
if(ch[x][0]) sz[x]+=sz[ch[x][0]];
if(ch[x][1]) sz[x]+=sz[ch[x][1]];
}
inline void route(int x){
int y=f[x],z=f[y],w=(ch[y][1]==x);
ch[y][w]=ch[x][w^1],f[ch[y][w]]=y;
ch[x][w^1]=y,f[y]=x;
f[x]=z;
if(z) ch[z][ch[z][1]==y]=x;
update(y),update(x);
}
inline void splay(int x){
for(int fa;fa=f[x];route(x))
if(f[fa]) ((ch[fa][1]==x)^(ch[f[fa]][1]==fa)) ? route(x):route(fa);
root=x;
}
inline void _insert(int x){
if(!root){
++tot,root=tot;sz[tot]=cnt[tot]=1,val[tot]=x;
ch[tot][0]=ch[tot][1]=f[tot]=0;
return;
}
int now=root,fa=0;
while(1)
{
if(x==val[now]) {++cnt[now];update(now),update(fa);splay(now);break;}
fa=now,now=ch[now][x>val[now]];
if(!now){
++tot;ch[tot][0]=ch[tot][1]=0,sz[tot]=cnt[tot]=1,val[tot]=x;
ch[fa][x>val[fa]]=tot,f[tot]=fa;
update(fa);splay(tot);
break;
}
}
}
inline int _rank(int x){//查找x的排名
int now=root,ans=0;
while(1)
{
if(x<val[now]) now=ch[now][0];
else{
ans+=(ch[now][0]?sz[ch[now][0]]:0);
if(x==val[now]) {splay(now);return ans+1;}
ans+=cnt[now],now=ch[now][1];
}
}
}
inline int _Rank(int x){//查找排名为x的数的大小
int now=root;
while(1)
{
if(ch[now][0]&&x<=sz[ch[now][0]]) now=ch[now][0];
else{
int tmp=(ch[now][0]?sz[ch[now][0]]:0)+cnt[now];
if(x<=tmp) return val[now];
x-=tmp,now=ch[now][1];
}
}
}
inline int _pre(){
int now=ch[root][0];
while(ch[now][1]) now=ch[now][1];
return now;
}
inline int _nex(){
int now=ch[root][1];
while(ch[now][0]) now=ch[now][0];
return now;
}
inline void _delete(int x){
_rank(x);
if(cnt[root]>1) {--cnt[root];update(root);return;}
if(!ch[root][0]&&!ch[root][1]) {_clear(root);root=0;return;}
int tmp=root,ls=ch[root][0],rs=ch[root][1];
if(!ls) {root=rs,f[root]=0,_clear(tmp);return;}
if(!rs) {root=ls,f[root]=0,_clear(tmp);return;}
splay(_pre());//前驱为0时 也就是此时root没有左子树 这样的话根就是0 反正_insert时就是错的错的 T_T 略略略不想改 上面还有两个if(!ls)啊.
ch[root][1]=rs,f[rs]=root;
_clear(tmp);update(root);
}
int main()
{
int n,opt,x;scanf("%d",&n);
for(int i=1;i<=n;++i)
{
scanf("%d%d",&opt,&x);
switch(opt)
{
case 1:_insert(x);break;
case 2:_delete(x);break;
case 3:printf("%d\n",_rank(x));break;
case 4:printf("%d\n",_Rank(x));break;
case 5:_insert(x);printf("%d\n",val[_pre()]);_delete(x);break;
case 6:_insert(x);printf("%d\n",val[_nex()]);_delete(x);break;
}
}
}
bzoj3224(普通平衡树 splay板子)
最新推荐文章于 2019-12-03 21:59:15 发布