猜猜数据结构(I Can Guess the Data Structurel!,UVA-11995 )

题目链接

https://vjudge.net/problem/UVA-11995

题意

给定一个数据结构,其支持两种操作:
1 x
2
操作1 x为插入一个值x,操作2删除一个元素并返回所删除元素的值。现要求你判断该数据结构属于队列、栈、优先队列哪种。

分析

模拟三种数据结构,然后与每次操作2的结果进行对比。一旦有一次操作不满足所模拟的数据结构的要求,就排除该数据结构。

代码

#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <stack>

using namespace std;

stack<int> sta;
queue<int> que;
priority_queue<int> pri;
void init()
{
    while(!que.empty()) que.pop();
    while(!sta.empty()) sta.pop();
    while(!pri.empty()) pri.pop();
}
int main()
{
    int n;
    while(cin>>n)
    {
        init();
        int fa=1,fb=1,fc=1; //初始化都为真
        for(int i=0;i<n;i++)
        {
            int op,x;
            cin>>op>>x;
            if(op==1)
            {
                //模拟三种操作
                que.push(x);
                sta.push(x);
                pri.push(x);
            }
            else
            {
                int a=1e4,b=1e4,c=1e4;//初始化为非x值
                //模拟三种操作
                if(!sta.empty()) //加非空条件防止运行错误
                {
                    a=sta.top();sta.pop();
                }
                if(!que.empty())
                {
                    b=que.front();que.pop();
                }

                if(!pri.empty())
                {
                    c=pri.top();pri.pop();
                }

                //用排除法去排除不满足的数据结构
                if(a!=x) fa=0;
                if(b!=x) fb=0;
                if(c!=x) fc=0;
            }
        }
        string ans;
        //判断属于哪一种
        int sum=fa+fb+fc;
        if(sum==0) ans="impossible";
        else if(sum==2 || sum==3) ans="not sure";
        else
        {
            if(fa) ans="stack";
            else if(fb) ans="queue";
            else ans="priority queue";
        }
        cout<<ans<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值