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


题意:给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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值