I Can Guess the Data Structure!
There is a bag-like data structure, supporting two operations:
1 x | Throw an element x into the bag. |
2 | Take out an element from the bag. |
Given a sequence of operations with return values, you’re going to guess the data structure. It isa stack (Last-In, First-Out), a queue (First-In, First-Out), a priority-queue (Always take out largerelements first) or something else that you can hardly imagine!
Input
There are several test cases. Each test case begins with a line containing a single integer n (1 ≤ n ≤1000). Each of the next n lines is either a type-1 command, or an integer 2 followed by an integer x.That means after executing a type-2 command, we get an element x without error. The value of xis always a positive integer not larger than 100. The input is terminated by end-of-file (EOF).OutputFor each test case, output one of the following:
stack | It’s definitely a stack. |
queue | It’s definitely a queue. |
priority queue | It’s definitely a priority queue. |
impossible | It can’t be a stack, a queue or a priority queue. |
not sure | It can be more than one of the three data structures mentionedabove. |
Sample Input
6
1 1
1 2
1 3
2 1
2 2
2 3
6
1 1
1 2
1 3
2 3
2 2
2 1
2
1 1
1 2
4
1 2
1 1
2 1
2 2
7
1 2
1 5
1 1
1 3
2 5
1 4
2 4
Sample Output
queue
not sure
impossible
stack
priority queue
题意:
输入多组数据,每组有t行,x为1时表示将y放入背包,x为2时表示将y从背包中取出。
由取出的顺序不同判断出是队列(先进先出),栈(先进后出),还是优先队列(每次取出最大的)或者这三者均不是或者两种及以上可能。
#include<stdio.h>
#include<queue>
#include<stack>
using namespace std;
int main()
{
int t;
while(~scanf("%d",&t))
{
queue<int>q;//定义队列
stack<int>s;//定义栈
priority_queue<int>p;//定义优先队列(默认从大到小排序)
int i,j,f[3],x,y;
for(i=0; i<3; i++)
f[i]=1;
for(i=0; i<t; i++)
{
scanf("%d%d",&x,&y);
if(x==1)
{
s.push(y);//入栈
q.push(y);//入队列
p.push(y);//入优先队列
}
else
{
if(!s.empty())
{
if(s.top()!=y)//如果取出的元素不等于栈顶元素
f[0]=0;
s.pop();//清除元素
}
else//当栈为空的时候,就不满足
f[0]=0;
if(!q.empty())
{
if(q.front()!=y)//如果取出的元素不等于队首元素
f[1]=0;
q.pop();
}
else
f[1]=0;//当队列为空的时候,就不满足
if(!p.empty())
{
if(p.top()!=y)//如果取出元素不等于队首(最大)元素
f[2]=0;
p.pop();
}
else
f[2]=0;
}
}
int sum=0;
for(i=0; i<3; i++)
{
if(f[i]==1)
sum++;
}
if(sum==0)//如果不满足以上三个条件
printf("impossible\n");
else if(sum>1)//当满足多个条件
printf("not sure\n");
else//满足一种条件
{
if(f[0]==1)
printf("stack\n");
else if(f[1]==1)
printf("queue\n");
else if(f[2]==1)
printf("priority queue\n");
}
}
return 0;
}