hdu 5818 (优先队列) Joint Stacks

题目:这里

题意: 两个类似于栈的列表,栈a和栈b,n个操作,push a x表示把数x放进a栈的栈底,pop b 表示将栈b的栈顶元素取出输出,并释放这个栈顶元素,merge a b表示把后面的那个

栈里的元素全部压进前面的那个栈里面,并且压入后前面的栈的所有元素按其进栈顺序排列然后后面的栈变为了空。

push和pop操作都还好,就是优先队列或者栈的操作,主要是merge操作,如果啊按照题目来模拟每次将后面的栈元素取出放入前面的栈,可能会超时,而超时的主要因素是每次都将

元素多的栈压入了元素少的栈,可以每次默认将栈1元素压入栈2,然后根据情况判断栈1和栈2到底哪个是栈a哪个是栈b,这样就解决了可能超时的问题,具体看代码。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<algorithm>
 5 #include<cmath>
 6 #include<stack>
 7 #include<queue>
 8 using namespace std;
 9 
10 const int M = 1e5 + 10;
11 struct node{
12    int x,y;
13    friend bool operator < (node a,node b){
14         return a.y<b.y;
15     }
16 }num[M];
17 priority_queue<node>a[2];
18 
19 int main()
20 {
21     int n,tem=0;
22     while (~scanf("%d",&n)&&n){
23         printf("Case #%d:
",++tem);
24         while (!a[0].empty()) a[0].pop();
25         while (!a[1].empty()) a[1].pop();
26         int ans=0,flag=0;
27         while (n--){
28             char str[10],op;
29             scanf("%s",str);scanf(" %c",&op);
30             if (strcmp(str,"push")==0){
31                 scanf(" %d",&num[++ans].x);
32                 num[ans].y=ans;
33                 if (op=='A') a[flag].push(num[ans]);
34                 else a[flag^1].push(num[ans]);
35             }
36             else if (strcmp(str,"pop")==0){
37                 if (op=='A') printf("%d
",a[flag].top().x),a[flag].pop();
38                 else printf("%d
",a[flag^1].top().x),a[flag^1].pop();
39             }
40             else{
41                 char ch;
42                 scanf(" %c",&ch);
43                 while (!a[1].empty()){
44                     a[0].push(a[1].top());
45                     a[1].pop();
46                 }
47                 if (op=='A'&&flag==1) flag=0;
48                 if (op=='B'&&flag==0) flag=1;
49             }
50         }
51     }
52     return 0;
53 }
原文地址:https://www.cnblogs.com/JJCHEHEDA/p/5762633.html