treap 模版

struct Treap {
    struct node {
        node *son[2];
        int key,siz,wei,cnt;
        node(int _key,node *f) {
            son[0]=son[1]=f;
            key=_key;siz=cnt=1;wei=rand();
        }
        void pushup() {
            siz=son[0]->siz+son[1]->siz+cnt;
        }
    }*null,*root;
    Treap() {
        null=new node(0,0);
        null->siz=null->siz=0;
        null->wei=inf;root=null;//  INF视情况而定
    }
    void rot(node* &rt,bool d) {
        node* c=rt->son[!d];rt->son[!d]=c->son[d];
        c->son[d]=rt;rt->pushup();c->pushup();rt=c;
    }
    void insert(const int &key,node* &rt) {
        if (rt==null) {
            rt=new node(key,null);return ;
        }
        if (key==rt->key) {
            rt->cnt++;rt->siz++;return ;
        }
        bool d=key>rt->key;
        insert(key,rt->son[d]);
        if (rt->wei>rt->son[d]->wei) rot(rt,!d);
        rt->pushup();
    }
    void remove(const int &key,node* &rt) {
        if (rt==null) return ;
        bool d=key>rt->key;
        if (key==rt->key) {
            if (rt->cnt>1) {
                rt->cnt--;rt->siz--;return ;
            }
            d=rt->son[0]->wei>rt->son[1]->wei;
            if (rt->son[d]==null) {
                delete rt;rt=null;return ;
            }
            rot(rt,!d);remove(key,rt->son[!d]);
        } else remove(key,rt->son[d]);
        rt->pushup();
    }
    node* select(int k,node* rt) {
        int s=rt->son[0]->siz+rt->cnt;
        if (k>=rt->son[0]->siz+1&&k<=s) return rt;
        if (s>k) return select(k,rt->son[0]);
        else return select(k-s,rt->son[1]);
    }
    int rank(const int &key,node* rt) {
        if (rt==null) return 0;
        int s=rt->son[0]->siz+rt->cnt;
        if (key==rt->key) return rt->son[0]->siz+1;
        if (key<rt->key) return rank(key,rt->son[0]);
        else return s+rank(key,rt->son[1]);
    }
    int pre(const int &k) {
        node* t=root;int ret=0;
        while (t!=null)
        if (t->key<k) ret=t->key,t=t->son[1];
        else t=t->son[0];
        return ret;
    }
    int sub(const int &k) {
        node* t=root;int ret=0;
        while (t!=null)
        if (t->key>k) ret=t->key,t=t->son[0];
        else t=t->son[1];
        return ret;
    }
};

 

posted @ 2017-01-04 11:49  jhz033  阅读(178)  评论(0编辑  收藏  举报