UVa 11995:I Can Guess the Data Structure!(数据结构练习)
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). The size of input file does not exceed 1MB.
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
Output for the Sample Input
queue not sure impossible stack priority queue
Rujia Liu's Present 3: A Data Structure Contest Celebrating the 100th Anniversary of Tsinghua University
Special Thanks: Yiming Li
Note: Please make sure to test your program with the gift I/O files before submitting!
数据结构练习。
这道题的题目是“猜猜数据结构”,题意就是给你一些输入输出数据,让你根据这些数据判断是什么数据结构。要猜的数据结构只有三种,栈(stack)、队列(queue)、优先队列(priority_queue)。输出有5种情况,前三种分别是确定了一种数据结构,第四种是三种数据结构都不符合,第五种是有2种或2种以上符合。
思路就是在程序中定义这三种数据结构,根据输入数据,产生各自的输出结果,分别与给定的输出输出对比。如果与测试数据不同,则这种数据结构不可能。最后记录下符合的数据结构的个数,分情况判断输出即可。
代码:
1 #include <iostream>
2 #include <queue>
3 #include <stack>
4 using namespace std;
5 int main()
6 {
7 int i,n;
8 while(cin>>n){
9 queue <int> q;
10 priority_queue <int> pq;
11 stack <int> s;
12 bool f[3] = {0};
13 for(i=1;i<=n;i++){
14 int a,b;
15 cin>>a>>b;
16 if(a==1){ //入
17 q.push(b);
18 pq.push(b);
19 s.push(b);
20 }
21 else{ //出
22 //依次对比
23 if(!f[0] && !q.empty()){
24 int x = q.front();
25 q.pop();
26 if(x!=b) f[0]=true;
27 }
28 else f[0]=true;
29
30
31 if(!f[1] && !pq.empty()){
32 int x = pq.top();
33 pq.pop();
34 if(x!=b) f[1]=true;
35 }
36 else f[1]=true;
37
38 if(!f[2] && !s.empty()){
39 int x = s.top();
40 s.pop();
41 if(x!=b) f[2]=true;
42 }
43 else f[2]=true;
44 }
45 }
46 //查找有几个符合输出
47 int num=0;
48 for(i=0;i<3;i++)
49 if(!f[i])
50 num++;
51 if(num==0)
52 cout<<"impossible"<<endl;
53 else if(num==1){
54 if(!f[0])
55 cout<<"queue"<<endl;
56 else if(!f[1])
57 cout<<"priority queue"<<endl;
58 else if(!f[2])
59 cout<<"stack"<<endl;
60 }
61 else
62 cout<<"not sure"<<endl;
63 }
64 return 0;
65 }
Freecode : www.cnblogs.com/yym2013