1051 Pop Sequence (25分)
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的情况:
(1)不在栈中且剩余空间不够让它进栈
(2)在栈中但栈顶不是它
如果不是这两种情况,就说明当前数字是可以通过进栈或者栈顶直接退栈得到的。遍历下一个数字,重复上述两种情况判断,遍历完之后,返回true,具体的可参考代码中的注释。
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include <queue>
#include<algorithm>
using namespace std;
int input[1001];
int stack[1001];
int stackpoint = 0;
int m, n, k;
bool judge(int* a) {
int max = 0;//这个变量记录进过栈的最大值,意思就是比max小的变量肯定进过栈
stackpoint = 0;//栈指针
for (int i = 1; i <= n; i++) {//遍历需要判断的数组
if (a[i] > max && m - stackpoint < a[i] - max) {
/*如果遍历到的数字大于max,说明该数字未进过栈,
如果要它进栈,需要剩余空间(m-stackpoint)能够压入max到a[i]间所有的数字,
如果剩余空间不够,返回false */
return false;
}
else if (a[i] <= max && a[i] != stack[stackpoint]) {
/*如果a[i]<=max,说明a[i]在栈里,这时如果a[i]!= 栈顶元素stack[stackpoint],则无法退栈,返回false*/
return false;
}
else {
for (int j = max + 1; j <= a[i]; j++) {//压入a[i]到max之间的元素,如果a[i]<=max这一步会跳过
stack[++stackpoint] = j;
}
max = a[i] > max ? a[i] : max;//max的值要根据a[i]的大小变换,因为有两种情况。
stackpoint--;//栈顶元素退栈
}
}
return true;
}
int main() {
cin >> m >> n >> k;
for (int i = 0; i < k; i++) {
for (int j = 1; j <= n; j++) {
cin >> input[j];
}
if (judge(input)) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
}