[Tyvj1728] 普通平衡树 - Splay模板

第三次A这题了,代码终于像点样子。


#include<cstdio>
#define Ms 100005
using namespace std;
int fa[Ms],ch[Ms][2],cnt[Ms],size[Ms],k[Ms],ind=0,root=0,m;
void debug(int p);
void update(int p){
    size[p]=size[ch[p][0]]+size[ch[p][1]]+cnt[p];
}
void rotate(int p){
    int q=fa[p],y=fa[q],x=ch[q][1]==p;
    ch[q][x]=ch[p][x^1];fa[ch[q][x]]=q;
    ch[p][x^1]=q;fa[q]=p;
    fa[p]=y;
    if(y)if(ch[y][0]==q)ch[y][0]=p;
    else if(ch[y][1]==q)ch[y][1]=p;
    update(q);update(p);
}
void splay(int x){
    for(int y;y=fa[x];rotate(x))
        if(fa[y])rotate((x==ch[y][0])==(y==ch[fa[y]][0])?y:x);
    root=x;
}
int search(int v){
    int p=root;
    while(p&&v!=k[p])p=ch[p][k[p]<v];
    return p;
}
void insert(int v){ 
    if(!root){
        root=++ind;k[root]=v;size[root]=cnt[root]=1;
        ch[root][0]=ch[root][1]=fa[root]=0;
    }
    else if(search(v)){
        int t=search(v);splay(t);
        size[t]++;cnt[t]++;
    }
    else{
        int x=root,y;
        for(;;){
            y=ch[x][k[x]<v];
            if(!y){
                y=++ind;k[y]=v;size[y]=cnt[y]=1;
                ch[x][k[x]<v]=y;ch[y][0]=ch[y][1]=0;fa[y]=x;break;
            }
            x=y;
        }
        splay(y);
    }
}
void remove(int p){
    if(!p)return;
    splay(p);
    if(cnt[p]>1){cnt[p]--;size[p]--;return;}
    int l=ch[p][0],r=ch[p][1],lm;lm=l;
    fa[l]=fa[r]=ch[p][0]=ch[p][1]=0;
    root=l;
    while(lm&&ch[lm][1])lm=ch[lm][1];
    if(!lm){
        root=r;return;
    }
    splay(lm);
    ch[lm][1]=r;if(r)fa[r]=lm;
    update(root);
}
int grank(int p){
    splay(p);
    return size[ch[p][0]]+1;
}
int kth(int _k){
    int p=root,k=_k;
    while(1){
        if(ch[p][0]){
            if(k>size[ch[p][0]]&&k<=size[ch[p][0]]+cnt[p])return p;
            if(k<=size[ch[p][0]])p=ch[p][0];
            else k-=(size[ch[p][0]]+cnt[p]),p=ch[p][1];
        }
        else{
            if(k<=cnt[p])return p;
            else k-=cnt[p],p=ch[p][1];
        }
    }
}
int prefix(int p){
    int t=ch[p][0];splay(p);
    while(t&&ch[t][1])t=ch[t][1];
    return t;
}
int suffix(int p){
    int t=ch[p][1];splay(p);
    while(t&&ch[t][0])t=ch[t][0];
    return t;
}
int main(){
    scanf("%d",&m);
    int c,t;
    for(int i=0;i<m;i++){
        scanf("%d%d",&c,&t);
        switch(c){
            case 1: insert(t);break;
            case 2: remove(search(t));break;
            case 3: printf("%d\n",grank(search(t)));break;
            case 4: printf("%d\n",k[kth(t)]);break;
            case 5: insert(t);printf("%d\n",k[prefix(search(t))]);remove(search(t));break;
            case 6: insert(t);printf("%d\n",k[suffix(search(t))]);remove(search(t));break;
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值