UVA - 11995 : 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 is a stack (Last-In, First-Out), a queue (First-In, First-Out), a priority-queue (Always take out larger elements 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 x is always a positive integer not larger than 100. The input is terminated by end-of-file (EOF).
Output
For 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 mentioned above.
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 2 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
给出一些数据放入闭包,根据输出猜测这个闭包是什么数据结构(栈,队列,优先队列,都不是,有两种以上可能)
用三种数据结构分别模拟即可。
Select Code
#include<iostream>
#include<queue>
#include<stack>
#include<string.h>
using namespace std;
int a[1000][2];
int n;
bool checks()
{
stack<int> s;
// cout<<1<<endl;
for(int i=0;i<1000;i++)
s.push(0);
int x;
for(int i=0;i<n;i++)
{
if(a[i][0]==1)
s.push(a[i][1]);
if(a[i][0]==2)
{
x=s.top();
s.pop();
if(x!=a[i][1])
return false;
}
}
return true;
}
bool checkq()
{
int x;
// cout<<1<<endl;
queue<int> q;
for(int i=0;i<n;i++)
{
if(a[i][0]==1)
q.push(a[i][1]);
if(a[i][0]==2)
{
if(q.empty())
return false;
x=q.front();
// cout<<x<<endl;
q.pop();
if(x!=a[i][1])
return false;
}
}
return true;
}
bool checkp()
{
int x;
priority_queue<int> p;
for(int i=0;i<1000;i++)
p.push(0);
for(int i=0;i<n;i++)
{
if(a[i][0]==1)
p.push(a[i][1]);
if(a[i][0]==2)
{
x=p.top();
p.pop();
if(x!=a[i][1])
return false;
}
}
return true;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
memset(a,0,sizeof(a));
for(int i=0;i<n;i++)
cin>>a[i][0]>>a[i][1];
bool s=checks();
bool q=checkq();
bool p=checkp();
if(s&&!q&&!p)
cout<<"stack"<<endl;
else
if(!s&&q&&!p)
cout<<"queue"<<endl;
else
if(!s&&!q&&p)
cout<<"priority queue" <<endl;
else
if(!s&&!q&&!p)
cout<<"impossible"<<endl;
else
//if(s&&q&&!p||s&&!q&&p||!s&&q&&p||s&&p&&q)
cout<<"not sure"<<endl;
}
return 0;
}