I Can Guess the Data Structure!
题意:
现在有一个容器,可能是栈,队列,或优先队列,给出元素进入容器和出容器的次序,看能否判断是哪个容器。
解题思路:
直接用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;
}