模拟栈

原题Joint Stacks

题意

三种操作,pop,push和merge,merge时按照元素的进栈先后排序

解析

用set存下元素出现的时间,开始的时候set[0]A,set[1]为B,posa为0,!posa为1,在merge的时候如果元素多的往元素少的堆转移的时候,我们还是把少的加入多的堆,然后posa=!posa即可。

代码

#include<stdio.h>
#include<set>
#define D long long
using namespace std;

D nu[100009];

int main(){
    int n;int t=1;
    while(1){
        scanf("%d",&n);
        if(n==0)break;
        printf("Case #%d:\n",t++);
        D now=0;set<D>s[2];int posa=0;
        char x[7];
        while(n--){ 
            scanf("%s",x);
            if(x[1]=='u'){
                scanf("%s",x);D mid;scanf("%lld",&mid);
                nu[++now]=mid;
                if(x[0]=='A')s[posa].insert(now);
                else s[!posa].insert(now);
            }
            else if(x[0]=='p'){
                scanf("%s",x);
                set<D>::iterator it;
                int mid;if(x[0]=='A')mid=posa;else mid=!posa;
                it=s[mid].end();it--;
                printf("%lld\n",nu[*it]);s[mid].erase(it);
            }
            else{
                scanf("%s",x);scanf("%s",x);
                if(x[0]=='B'){
                    if(s[!posa].size()<s[posa].size()){
                        set<D>::iterator it=s[!posa].begin();
                        while(it!=s[!posa].end()){
                            s[posa].insert(*it);it++;
                        }s[!posa].clear();
                    }
                    else{
                        set<D>::iterator it=s[posa].begin();
                        while(it!=s[posa].end()){
                            s[!posa].insert(*it);it++;
                        }s[posa].clear();
                        posa=!posa;
                    }
                }
                else{
                    if(s[posa].size()<s[!posa].size()){
                        set<D>::iterator it=s[posa].begin();
                        while(it!=s[posa].end()){
                            s[!posa].insert(*it);it++;
                        }s[posa].clear();
                    }
                    else{
                        set<D>::iterator it=s[!posa].begin();
                        while(it!=s[!posa].end()){
                            s[posa].insert(*it);it++;
                        }s[!posa].clear();
                        posa=!posa;
                    }
                }
            }
        }
    }
    return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值