poj 3481 Double Queue(平衡树,SBT)


poj 3481 Double Queue


平衡树模板题,练手


#include<stdio.h>
#include<string.h>
#define MAXN 100005
struct node
{
    int l,r;
    int key,id;
    int size;
}t[MAXN];
int top,root;
void lRotate(int &p)
{
    int rch=t[p].r;
    t[p].r=t[rch].l;
    t[rch].l=p;
    
    t[rch].size=t[p].size;
    t[p].size=t[t[p].l].size+t[t[p].r].size+1;
    
    p=rch;
}
void rRotate(int &p)
{
    int lch=t[p].l;
    t[p].l=t[lch].r;
    t[lch].r=p;
    
    t[lch].size=t[p].size;
    t[p].size=t[t[p].l].size+t[t[p].r].size+1;
    
    p=lch;
}
void maintain(int &p,bool flag)
{
    if(!flag)
    {
        if(t[t[t[p].l].l].size>t[t[p].r].size)//LL
            rRotate(p);
        else if(t[t[t[p].l].r].size>t[t[p].r].size)//LR
            lRotate(t[p].l),
            rRotate(p);
        else return ;
    }
    else
    {
        if(t[t[t[p].r].r].size>t[t[p].l].size)
            lRotate(p);
        else if(t[t[t[p].r].l].size>t[t[p].l].size)
            rRotate(t[p].r),
            lRotate(p);
        else return ;
    }
    maintain(t[p].l, false);
    maintain(t[p].r, true);
    maintain(p, false);
    maintain(p, true);
}
void insert(int &p,int key,int id)
{
    if(p==0)
    {
        p=++top;
        t[p].l=t[p].r=0;
        t[p].size=1;
        t[p].key=key,t[p].id=id;
    }
    else
    {
        t[p].size++;
        if(key<t[p].key) insert(t[p].l,key,id);
        else insert(t[p].r,key,id);
        maintain(p, key>=t[p].key);
    }
}
int remove(int &p,int key)
{
    t[p].size--;
    if(t[p].key==key||
       (key<t[p].key&&t[p].l==0)||
       (key>t[p].key&&t[p].r==0))
    {
        int retkey=t[p].key;
        if(t[p].l&&t[p].r)
            t[p].key=remove(t[p].l,t[p].key+1);
        else
            p=t[p].l+t[p].r;
        return retkey;
    }
    else if(key<t[p].key) return remove(t[p].l,key);
    else return remove(t[p].r,key);
}
int getmin()
{
    int p=root;
    while(t[p].l) p=t[p].l;
    printf("%d\n",t[p].id);
    return t[p].key;
}
int getmax()
{
    int p=root;
    while(t[p].r) p=t[p].r;
    printf("%d\n",t[p].id);
    return t[p].key;
}
int main()
{
    top=root=0;
    int op,id,key;
    while(scanf("%d",&op)!=EOF&&op)
    {
        if(op==1)
        {
            scanf("%d%d",&id,&key);
            insert(root,key,id);
        }
        else if(op==2)
        {
            int temp=getmax();
            remove(root,temp);
        }
        else
        {
            int temp=getmin();
            remove(root,temp);
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值