UVA 11995:I Can Guess the Data Structure!(水)

本篇博客介绍了一个编程问题的解决方法,通过模拟栈、队列和优先队列的操作来判断输入序列可能对应的数据结构类型。针对每种数据结构,采用标志位记录是否符合输入序列的要求,并根据最终标志位的状态输出相应的数据结构名称。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I Can Guess the Data Structure!

Time limit:1000 ms OS:Linux

点击查看题目内容

题意:

现在有一个容器,可能是栈,队列,或优先队列,给出元素进入容器和出容器的次序,看能否判断是哪个容器。

解题思路:

直接用stack,queue和priority_queue来模拟,如果出现了出容器元素不符,则说明不可能是这个容器,用三个flag来存储其可能性,如果有多个flag为1,输出
not sure ,全为0输出impossible,只有一个flag为1就逐一判断了。

第一次由于没有在top/front前判断一下容器是否为空,导致RE。


Code:

#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;

stack<int> s;
queue<int> q;
priority_queue<int> pq;


int main()
{
    int n;
    while(cin>>n)
    {
        while(!s.empty())
            s.pop();
        while(!q.empty())
            q.pop();
        while(!pq.empty())
            pq.pop();
        int o,x;
        int flag1=1,flag2=1,flag3=1;
        for(int i=0;i<n;i++)
        {
            cin>>o>>x;
            if(flag1)
            {
                if(o==1)
                    s.push(x);
                else
                {
                    if(!s.empty()&&s.top()==x)
                        s.pop();
                    else
                        flag1=0;
                }
            }
            if(flag2)
            {
                if(o==1)
                    q.push(x);
                else
                {
                    if(!q.empty()&&q.front()==x)
                        q.pop();
                    else
                        flag2=0;
                }
            }
            if(flag3)
            {
                if(o==1)
                    pq.push(x);
                else
                {
                    if(!pq.empty()&&pq.top()==x)
                        pq.pop();
                    else
                        flag3=0;
                }
            }
        }
        if(flag1+flag2+flag3>1)
            cout<<"not sure"<<endl;
        else if(flag1+flag2+flag3==0)
            cout<<"impossible"<<endl;
        else if(flag1)
            cout<<"stack"<<endl;
        else if(flag2)
            cout<<"queue"<<endl;
        else
            cout<<"priority queue"<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值