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
题意
给定一个最多能存 M 个数字的栈,将 1∼N 按顺序压入栈中,过程中可随机弹出栈顶元素。
当 N 个数字都经历过入栈和出栈后,我们按照元素出栈的顺序,可以得到一个弹出序列。
现在给定一系列 1∼N 的随机排列序列,请你判断哪些序列可能是该栈的弹出序列。
例如,当 N=7,M=5 时,1, 2, 3, 4, 5, 6, 7可能是该栈的弹出序列,而 3, 2, 1, 7, 5, 6, 4 不可能是该栈的弹出序列。
思路
这题是一道栈模拟的题目,每次模拟操作只有两个选择:
1.推入元素,即如果当前栈顶元素不等于当前需要输出的元素,则推入新的元素。
2.弹出元素,即如果当前栈顶元素等于当前需要输出的元素,则弹出栈顶元素,直至不相等为止。
而判断该弹出序列是否满足要求同样有两个依据:
1.栈中元素不能大于 m 。
2.做完所有操作后,栈中不能有元素即所有栈顶元。
代码
#include<bits/stdc++.h> using namespace std; const int N = 1010; int a[N]; int m, n, k; bool check() { stack<int> stk; for (int i = 1, j = 0; i <= n; i++) { stk.push(i); //已经超出栈的容量,则返回false if (stk.size() > m) return false; //判断当前输出的元素是否与栈顶元素相等 while (stk.size() && stk.top() == a[j]) { stk.pop(); j++; } } return stk.empty(); } int main() { cin >> m >> n >> k; while (k--) { for (int i = 0; i < n; i++) cin >> a[i]; if (check()) puts("YES"); else puts("NO"); } return 0; }