poj3481 Double Queue

来源:互联网 发布:怎么创建数据库实例 编辑:程序博客网 时间:2024/06/06 00:57

题面在这里
题目大意:
有一些人,每个人有一个名字和优先级。初始时队列为空。现在有3种操作:插入一个人;弹出优先级最大的那个人;弹出优先级最小的那个人。

做法:
平衡树练习。直接上代码。

/*************************************************************    Problem: poj 3481 Double Queue    User: fengyuan    Language: C++    Result: Accepted    Time: 204 ms    Memory: 1.8 MB    Submit_Time: 2017-12-09 17:23:38*************************************************************/#include<cstdio>#include<cstring>#define rep(i, x, y) for (int i = (x); i <= (y); i ++)#define down(i, x, y) for (int i = (x); i >= (y); i --)#define mid ((l+r)/2)#define lc (o<<1)#define rc (o<<1|1)#define pb push_back#define mp make_pair#define PII pair<int, int>#define F first#define S second#define B begin()#define E end()using namespace std;typedef long long LL;//headconst int N = 1000010;int rt, tot;int fa[N], ch[N][2], data[N], val[N];inline void clear(int x){ fa[x] = ch[x][0] = ch[x][1] = data[x] = val[x] = 0; }inline void rot(int x){    int y = fa[x], z = fa[y];    int f = ch[y][1] == x;    ch[y][f] = ch[x][f^1]; if (ch[x][f^1]) fa[ch[x][f^1]] = y;    fa[x] = z; if (z) ch[z][ch[z][1] == y] = x;    fa[y] = x; ch[x][f^1] = y;}inline void splay(int x, int top){    while (fa[x] != top){        int y = fa[x], z = fa[y];        if (z != top) rot(((ch[z][0] == y) == (ch[y][0] == x)) ? y : x);        rot(x);    } if (!top) rt = x;}inline void insert(int K, int v){    int x = rt;    if (!rt){        x = rt = ++ tot;        data[x] = v; val[x] = K;        fa[x] = ch[x][0] = ch[x][1] = 0;        return;    }    while (x){        int &y = ch[x][v > data[x]];        if (!y){            y = ++ tot;            data[y] = v; val[y] = K;            fa[y] = x; ch[y][0] = ch[y][1] = 0;            x = y; return;        } x = y;    } splay(x, 0);}inline int findMax(int x){ while (ch[x][1]) x = ch[x][1]; return x; }inline int findMin(int x){ while (ch[x][0]) x = ch[x][0]; return x; }inline void del(int x){    splay(x, 0);    if (!ch[x][0] && !ch[x][1]){ clear(rt); rt = 0; return; }    if (!ch[x][0]){ rt = ch[x][1]; fa[rt] = 0; return; }    if (!ch[x][1]){ rt = ch[x][0]; fa[rt] = 0; return; }    int p = findMax(ch[x][0]), rtt = rt; splay(p, 0);    ch[rt][1] = ch[rtt][1]; fa[ch[rtt][1]] = rt;    clear(rtt);}int main(){    int opt;    while (~scanf("%d", &opt) && opt){        if (opt == 1){            int x, y; scanf("%d%d", &x, &y);            insert(x, y);        } else if (opt == 2){            int x = findMax(rt);            if (!x){ puts("0"); continue; }            printf("%d\n", val[x]);            del(x);        } else {            int x = findMin(rt);            if (!x){ puts("0"); continue; }            printf("%d\n", val[x]);            del(x);        }    }    return 0;}