FHQ Treap

· · 个人记录

namespace FHQTreap
{
    struct node
    {
        ll s[2],ky,cnt,siz,pri;
    }t[MAXN];
    ll cnt,root;
    ll newnode(ll x)
    {
        t[++cnt]={{0,0},x,1,1,rand()};
        return cnt;
    }
    void pushup(ll u)
    {
        ll ls=t[u].s[0],rs=t[u].s[1];
        t[u].siz=t[ls].siz+t[rs].siz;
        t[u].siz+=t[u].cnt;
    }
    void split(ll u,ll x,ll &l,ll &r)
    {
        if(!u)
        {
            l=r=0;
            return ;
        }
        if(t[u].ky<=x)
        {
            l=u;
            split(t[u].s[1],x,t[u].s[1],r);
        }
        else
        {
            r=u;
            split(t[u].s[0],x,l,t[u].s[0]);
        }
        pushup(u);
    }
    ll merge(ll l,ll r)
    {
        if(!l||!r)return l+r;
        if(t[l].pri>t[r].pri)
        {
            t[l].s[1]=merge(t[l].s[1],r);
            pushup(l);
            return l;
        }
        t[r].s[0]=merge(l,t[r].s[0]);
        pushup(r);
        return r;
    }
    void add(ll x)
    {
        ll l,r,u;
        split(root,x,l,r);
        split(l,x-1,l,u);
        if(t[u].ky==x)
        {
            t[u].cnt++;
            t[u].siz++;
            root=merge(merge(l,u),r);
            return ;
        }
        root=merge(merge(l,newnode(x)),r);
    }
    void del(ll x)
    {
        ll l,r,u;
        split(root,x,l,r);
        split(l,x-1,l,u);
        if(t[u].cnt>1)
        {
            t[u].cnt--;
            t[u].siz--;
            root=merge(merge(l,u),r);
            return ;
        }
        root=merge(l,r);
    }
    ll get(ll x,bool y)
    {
        ll l,r,u;
        if(!y)
        {
            split(root,x-1,l,r);
            u=l;
        }
        else
        {
            split(root,x,l,r);
            u=r;
        }
        while(t[u].s[y^1])
        {
            u=t[u].s[y^1];
        }
        root=merge(l,r);
        return u;
    }
    ll rk(ll x)
    {
        ll l,r;
        split(root,x-1,l,r);
        ll u=t[l].siz;
        root=merge(l,r);
        return u;
    }
    ll kth(ll x)
    {
        x++;
        ll y=root;
        if(t[y].siz<x)return 0;
        while(1)
        {
            ll ls=t[y].s[0];
            if(t[ls].siz>=x)
            {
                y=ls;
                continue;
            }
            x-=t[ls].siz;
            if(t[y].cnt>=x)
            {
                return y;
                continue;
            }
            x-=t[y].cnt;
            y=t[y].s[1];
        }
    }
    void ask(ll x)
    {
        if(t[x].s[0])ask(t[x].s[0]);
        cout<<t[x].ky<<" ";
        if(t[x].s[1])ask(t[x].s[1]);
    }
}using namespace FHQTreap;