1051 Pop Sequence

Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, ..., N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.

Input Specification:

Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): M (the maximum capacity of the stack), N (the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N numbers. All the numbers in a line are separated by a space.

Output Specification:

For each pop sequence, print in one line "YES" if it is indeed a possible pop sequence of the stack, or "NO" if not.

Sample Input:

5 7 5
1 2 3 4 5 6 7
3 2 1 7 5 6 4
7 6 5 4 3 2 1
5 6 4 3 7 2 1
1 7 6 5 4 3 2
 

Sample Output:

YES
NO
NO
YES
NO

题意:

  按照给定的顺序依次进栈,栈顶元素出战的顺序随意。问一个给定的序列是不是出栈的序列。

思路:

  模拟。根据给定的序列依次入栈,入栈的过程中,如果栈顶元素与所给序列查询的位置处元素相等,则出栈,查询位置向后移动一位。另外,容器的大小有限,如果入栈的过程中,容器中的元素超出所给容量的话,输出NO即可。

Code:

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 int main() {
 6     int m, n, k;
 7     cin >> m >> n >> k;
 8 
 9     for (int i = 0; i < k; ++i) {
10         vector<int> seq(n);
11         for (int j = 0; j < n; ++j) cin >> seq[j];
12         int cur = 0;
13         stack<int> s;
14         for (int j = 1; j <= n; ++j) {
15             s.push(j);
16             if (s.size() > m) break;
17             while (!s.empty() && s.top() == seq[cur]) {
18                 s.pop();
19                 cur++;
20             }
21         }
22         if (cur == n)
23             cout << "YES" << endl;
24         else
25             cout << "NO" << endl;
26     }
27     return 0;
28 }

 

posted @ 2020-05-08 17:23  Veritas_des_Liberty  阅读(157)  评论(0编辑  收藏  举报