hdu-5818-Joint Stacks-栈模拟/左偏树

来源:互联网 发布:啪啪啪软件下载 编辑:程序博客网 时间:2024/04/30 05:30


题意:给A,B两个栈,

三种操作,push pop, merge 

可以直接模拟,因为保证了无pop空操作。

不过也是左偏树的经典操作咯。


nlogn复杂度

//左偏树,hdu5818#include <bits/stdc++.h>using namespace std;struct node{    int t,x;    node(){}    node(int a,int b)    {        t=a,x=b;    }    bool operator <(const node &b)const    {        return t<b.t;    }};const int maxn = 152400;node v[maxn];int tot,  l[maxn], r[maxn], d[maxn];//id[x]表示x所在树的编号int Merge(int x, int y){    if(!x) return y;    if(!y) return x;    if(v[x] < v[y]) swap(x, y);    r[x] = Merge(r[x], y);    if(d[l[x]] < d[r[x]]) swap(l[x], r[x]);    d[x] = d[r[x]] + 1;    return x;}int init(node x){    tot++;    v[tot] = x;    l[tot] = r[tot] = d[tot] = 0;    return tot;}int Insert(int x, node y){    return Merge(x, init(y));}node top(int x){    return v[x];}int pop(int x){    return Merge(l[x], r[x]);}char op[30], str[30], str2[30];int val;int main(){    int cnt = 1;    int N;    while(scanf("%d", &N)&& N)    {        memset(v, 0, sizeof(v));        memset(l, 0, sizeof(l));        memset(r, 0, sizeof(r));        memset(d, 0, sizeof(d));        tot =   0;        printf("Case #%d:\n", cnt++);        int posA = init(node(-1, -1));        int posB = init(node(-2, -1));        for(int i = 1; i <= N; ++i)        {            scanf("%s%s", op, str);            if(op[1] == 'u')            {                scanf("%d", &val);                if(str[0] == 'A')                {                    posA = Insert(posA, node(i, val));                }                else                {                    posB = Insert(posB, node(i, val));                }            }            else if(op[1] == 'o')            {                node ans;                if(str[0] == 'A')                {                    ans = top(posA);                    posA = pop(posA);                }                else                {                    ans = top(posB);                    posB = pop(posB);                }                printf("%d\n", ans.x);            }            else if(op[1] == 'e')            {                scanf("%s", str2);                if(str[0] == 'A')                {                    posA = Merge(posA, posB);                    posB = init(node(-1, -1));                }                else                {                    posB = Merge(posA, posB);                    posA = init(node(-1, -1));                }            }        }    }    return 0;}


0 0
原创粉丝点击