poj 3481 Double Queue (SBT)

来源:互联网 发布:超极本推荐2017知乎 编辑:程序博客网 时间:2024/06/06 16:39

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

#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>using namespace std;#define maxn 10000000#define INF 2000000000int 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