ZOJ 3210 A Stack or A Queue?
题目链接:ZOJ 3210
| Describe: |
|
Do you know stack and queue? They're both important data structures. A stack is a "first in last out" (FILO) data structure and a queue is a "first in first out" (FIFO) one. Here comes the problem: given the order of some integers (it is assumed that the stack and queue are both for integers) going into the structure and coming out of it, please guess what kind of data structure it could be - stack or queue? Notice that here we assume that none of the integers are popped out before all the integers are pushed into the structure. |
| Input: |
|
There are multiple test cases. The first line of input contains an integer T (T <= 100), indicating the number of test cases. Then T test cases follow. Each test case contains 3 lines: The first line of each test case contains only one integer N indicating the number of integers (1 <= N <= 100). The second line of each test case contains N integers separated by a space, which are given in the order of going into the structure (that is, the first one is the earliest going in). The third line of each test case also contains N integers separated by a space, whick are given in the order of coming out of the structure (the first one is the earliest coming out). |
| Output: |
| For each test case, output your guess in a single line. If the structure can only be a stack, output "stack"; or if the structure can only be a queue, output "queue"; otherwise if the structure can be either a stack or a queue, output "both", or else otherwise output "neither". |
| Sample Input: |
| 4 3 1 2 3 3 2 1 3 1 2 3 1 2 3 3 1 2 1 1 2 1 3 1 2 3 2 3 1 |
| Sample Output: |
| stack queue both neither |
题目大意:
若干样例,每个样例两个序列,分别表示输入数据结构前,后从数据结构输出后的序列,让你判断该数据结构是stack还是queue,或者两者都是,亦或者两者都不是。
解题思路:
水题,建个stack,queue按照题目要求来,看看最后到底是stack还是queue。
AC代码:
1 #include <cstdio> 2 #include <iostream> 3 #include <stack> // 不要忘了头文件 4 #include <queue> 5 using namespace std; 6 int main() 7 { 8 int t,n,x,isstack,isqueue; // isstack和isqueue是标志变量 9 cin >> t; 10 while(t--) 11 { 12 isstack = isqueue = 1; // 假设初始状态既为stack也为queue 13 stack<int> s; 14 queue<int> q; 15 cin >> n; 16 for(int i = 1; i <= n; i++) // 读入 17 { 18 cin >> x; 19 s.push(x); 20 q.push(x); 21 } 22 for(int i = 1; i <= n; i++) // 查看输出是否相同 23 { 24 cin >> x; 25 if(isstack && s.top() == x) s.pop(); 26 else isstack = 0; 27 if(isqueue && q.front() == x) q.pop(); 28 else isqueue = 0; 29 } 30 // 按要求输出 31 if(isqueue == 1 && isstack == 1) cout << "both" << endl; 32 else if(isqueue == 1 && isstack == 0) cout << "queue" << endl; 33 else if(isqueue == 0 && isstack == 1) cout << "stack" << endl; 34 else if(isqueue == 0 && isstack == 0) cout << "neither" << endl; 35 } 36 return 0; 37 }
小结:此题主要是熟练一下queue的一些操作

浙公网安备 33010602011771号