数据结构 ( 优先队列&&栈 )——HDU 5818 ( 2016 Multi-University Training Contest 7 1010 )

来源:互联网 发布:iso下载软件 编辑:程序博客网 时间:2024/05/17 08:36
  • 题目链接:
    http://acm.hdu.edu.cn/showproblem.php?pid=5818

  • 分析:

    对栈做三种操作:
    push A x 把x元素压入A中
    pop B 删除B中最上面的元素并输出该元素
    merge B A合并A到B中,合并后B中的元素顺序和之前压入的顺序一样(就是从头开始把之前的压入操作都只对B执行一遍)

  • 题解:
    用一个数据结构存储值和序号,使用三个优先队列,按序号排序,合并的时候全部合并到第三个优先队列里取,同时清空A和B,合并后查询的时候,若A,B中没有元素了,就取C里的最上面元素,能够保证题中要求顺序!

-参考代码:

#include<iostream>#include<cstdiO>#include<queue>using namespace std;struct stk{    int time,num;    bool operator<(const stk&a) const{        return time<a.time;    }}sta;priority_queue<stk> c;priority_queue<stk> a;priority_queue<stk> b;int main(){    int n;    int ca = 1;    while(~scanf("%d", &n) && n)    {        printf("Case #%d:\n", ca++);        while(!a.empty()) a.pop();        while(!b.empty()) b.pop();        while(!c.empty()) c.pop();        int i=0;        while(n--) {            char op[10];            scanf("%s", op);            if(op[1] == 'u') {                scanf("%s",op);                int x;                scanf("%d",&x);                if(op[0] == 'A') {                    sta.num=x;                    sta.time=i++;                    a.push(sta);                }                else {                    sta.num=x;                    sta.time=i++;                    b.push(sta);                }            }            else if(op[1] == 'o') {                scanf("%s",op);                if(op[0] == 'A') {                    if(!a.empty()) {                        printf("%d\n",a.top().num);                        a.pop();                    }                    else {                        printf("%d\n",c.top().num);                        c.pop();                    }                }                else if(op[0]=='B'){                    if(!b.empty()) {                        printf("%d\n",b.top().num);                        b.pop();                    }                    else {                        printf("%d\n",c.top().num);                        c.pop();                    }                }            }            else {                scanf("%s",op);                while(!a.empty()) {                    c.push(a.top());                    a.pop();                }                while(!b.empty()) {                    c.push(b.top());                    b.pop();                }                scanf("%s",op);            }        }    }}
0 0
原创粉丝点击