伸展树模板

已过的题:HDU 4585

/** ---- SPLAY ---- **/
int ch[maxn][2],fa[maxn],size[maxn];
int key[maxn],pos[maxn];
int tot,root,sroot;
void Splay_Init(){
    tot = 1;
    root = sroot = 0;
    ch[0][0] = ch[0][1] = 0;
    fa[0] = 0;
    key[0] = INF;
    size[0] = 0;
}
int NewNode(int FA,int k,int p){
    ch[tot][0] = ch[tot][1] = 0;
    fa[tot] = FA;
    size[tot] = 1;
    key[tot] = k,pos[tot] = p;
    return tot++;
}
void PushUp(int rt){size[rt] = 1 + size[ch[rt][0]] + size[ch[rt][1]];}
void rotate(int rt,int kind){
    int prt = fa[rt];
    ch[prt][kind] = ch[rt][!kind];fa[ch[rt][!kind]] = prt;
    ch[fa[prt]][ch[fa[prt]][1] == prt] = rt;fa[rt] = fa[prt];
    ch[rt][!kind] = prt;fa[prt] = rt;
    PushUp(prt);PushUp(rt);
}
void Splay(int rt,int goal){
    while(fa[rt] != goal){
        if(fa[fa[rt]] == goal) rotate(rt,ch[fa[rt]][1] == rt);
        else{
            int prt = fa[rt],kind = (ch[fa[prt]][1] == prt);
            if(ch[prt][kind] == rt) rotate(rt,kind),rotate(rt,kind);
            else rotate(rt,!kind),rotate(rt,kind);
        }
    }
    if(fa[rt] == sroot) root = rt;
}
void Insert(int rt,int k,int p){
    while(ch[rt][k > key[rt]]) rt = ch[rt][k > key[rt]];
    rt = (ch[rt][k > key[rt]] = NewNode(rt,k,p));
    Splay(rt,sroot);
}
int Find(int rt,int k){
    while(ch[rt][k >= key[rt]])
        if(k == key[rt]) return rt;
        else rt = ch[rt][k >= key[rt]];
    return sroot;
}
int Find_Pre(int rt,int k){
    rt = Find(rt,k);
    Splay(rt,sroot);
    if(ch[rt][0] == sroot) return sroot;
    else rt = ch[rt][0];
    while(ch[rt][1]) rt = ch[rt][1];
    return rt;
}
int Find_Next(int rt,int k){
    rt = Find(rt,k);
    Splay(rt,sroot);
    if(ch[rt][1] == sroot) return sroot;
    else rt = ch[rt][1];
    while(ch[rt][0]) rt = ch[rt][0];
    return rt;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值