poj 3481 Double Queue (SBT)

题意:给定集合,每次插入和删除元素,求最数和最小数。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;

#define maxn 10000000
#define INF 2000000000
int sz[maxn],ch[maxn][2];
int key[maxn],val[maxn],cnt;

void Rotate(int &x,int f){
    int y = ch[x][!f];
    ch[x][!f] = ch[y][f];
    ch[y][f] = x;
    sz[y] = sz[x];
    sz[x] = sz[ch[x][0]] + sz[ch[x][1]] + 1;
    x = y;
}

void Maintain(int &x,int f){
    if(sz[ch[ch[x][f]][f]] > sz[ch[x][!f]])  Rotate(x,!f);
    else if(sz[ch[ch[x][f]][!f]] > sz[ch[x][!f]]){
        Rotate(ch[x][f],f);Rotate(x,!f);
    }
    else return;
    Maintain(ch[x][0],0);
    Maintain(ch[x][1],1);
    Maintain(x,1);
    Maintain(x,0);
}

void Insert(int &x, int k, int p){
    if(x==0){
        x = ++cnt;sz[x] = 1;
        ch[x][0] = ch[x][1] = 0;
        key[x] = k;val[x]=p;
    }
    else{
        sz[x]++;
        if(p < val[x])  Insert(ch[x][0],k,p);
        else Insert(ch[x][1],k,p);
        Maintain(x, p>=val[x]);
    }
}

int Remove(int &x,int k){
    int d_key;
    if(!x)  return 0;
    sz[x]--;
    if(val[x]==k || (!ch[x][0] && k<val[x]) || (!ch[x][1] && k>val[x])){
        d_key = x;
        if(ch[x][0] && ch[x][1]){
            int t=Remove(ch[x][0],k+1);
            key[x]=key[t];
            val[x]=val[t];
        }
        else x = ch[x][0] + ch[x][1];
        return d_key;
    }
    else return Remove(k<val[x]?ch[x][0]:ch[x][1],k);
}

int Get_max(int x){
    while(ch[x][1]) x=ch[x][1];
    return x;
}

int Get_min(int x){
    while(ch[x][0]) x=ch[x][0];
    return x;
}


int main(){
    //freopen("1.txt","r",stdin);
    int id,a,b,root=0;cnt=0;
    while(scanf("%d",&id)!=EOF){
        if(id==0) break;
        else if(id==2){
            if(root==0) printf("0\n");
            else{
                int t = Get_max(root);
                printf("%d\n",key[t]);
                Remove(root,val[t]);
            }
        }
        else if(id==3){
            if(root==0) printf("0\n");
            else{
                int t = Get_min(root);
                printf("%d\n",key[t]);
                Remove(root,val[t]);
            }
        }
        else{
            scanf("%d%d",&a,&b);
            Insert(root,a,b);
        }
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值