FHQtreap

#include<bits/stdc++.h>
#define inf 2147483647
using namespace std;
const int N=100010;
int ch[N][2],val[N],key[N],sz[N],tot;
struct FHQtreap{
    int rt,x,y,z;
    inline void pushup(int x){
        sz[x]=1+sz[ch[x][0]]+sz[ch[x][1]];
    }
    int new_node(int v){
        sz[++tot]=1;
        val[tot]=v;
        key[tot]=rand();
        return tot;
    }
    int merge(int x,int y){
        if(!x||!y)return x+y;
        if(key[x]<key[y]){
            ch[x][1]=merge(ch[x][1],y);
            pushup(x);
            return x;
        }else{
            ch[y][0]=merge(x,ch[y][0]);
            pushup(y);
            return y;
        }
    }
    void split(int now,int k,int &x,int &y){
        if(!now)x=y=0;
        else{
            if(val[now]<=k)x=now,split(ch[now][1],k,ch[now][1],y);
            else y=now,split(ch[now][0],k,x,ch[now][0]);
            pushup(now);
        }
    }
    int kth(int now,int k){
        while(1){
            if(k<=sz[ch[now][0]])now=ch[now][0];
            else if(k==sz[ch[now][0]]+1)return now;
            else k-=sz[ch[now][0]]+1,now=ch[now][1];
        }
    }
    void insert(int a){
        split(rt,a,x,y);
        rt=merge(merge(x,new_node(a)),y);
    }
    void erase(int a){
        split(rt,a,x,z);
        split(x,a-1,x,y);
        rt=merge(merge(x,merge(ch[y][0],ch[y][1])),z);
    }
    int rnk(int a){
        split(rt,a-1,x,y);
        int ret=sz[x];
        rt=merge(x,y);
        return ret;
    }
    int kth(int a){
        return val[kth(rt,a+1)];
    }
    int pre(int a){
        split(rt,a-1,x,y);
        int ret=val[kth(x,sz[x])];
        rt=merge(x,y);
        return ret;
    }
    int suc(int a){
        split(rt,a,x,y);
        int ret=val[kth(y,1)];
        rt=merge(x,y);
        return ret;
    }
    FHQtreap(){
        insert(-inf);
        insert(inf);
    }
}tr;
int n;
int main(){
//	freopen("1.in","r",stdin);
    cin>>n;
    int x,y,z;
    for(int i=1;i<=n;++i){
        int how,a;
        scanf("%d%d",&how,&a);
        if(how==1){
        	tr.insert(a);
        }
        if(how==2){
        	tr.erase(a);
        }
        if(how==3){
            printf("%d\n",tr.rnk(a));
        }
        if(how==4){
            printf("%d\n",tr.kth(a));
        }
        if(how==5){
            printf("%d\n",tr.pre(a));
        }
        if(how==6){
            printf("%d\n",tr.suc(a));
        }
    }
}
posted @ 2019-07-24 15:18  整理者  阅读(206)  评论(0编辑  收藏  举报