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的栈,从栈底到顶的依次push为1- n, 给定k次枚举,判断是否能按照输入的要求通过依次pop,输出得到刚刚输入的值, 如果能输出YES
, 否则NO
, 并且stack中最大容量为m, 如果超过m的话, 也算NO
。 -
思路过程:
每次都将1-n的数push进stack中, 之后栈顶和输入的a[idx]比较,如果相同的话,idx指向a中的下一个位置, stack要pop出栈顶元素,一直检测此条件,相同并且栈不为空就一直pop, 不满足条件时就继续push。最终stack中存在元素或者中间的过程stack存储的元素个数超过m,输出no, 否者为yes。 此过程枚举k次即可。
解题代码
c模拟stack很简洁, c编译改一下头文件, 看了很多其他人写的c版本貌似没看到 比我这18行精简的了吧:
#include <cstdio>
int m, n, k, a[1010];
int main(){
scanf("%d %d %d", &m, &n, &k);
while (k --){
int st[1010], tt = 1, idx = 1, flag = 0;
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
for (int i = 1; i <= n; i++){
st[tt] = i;
if (tt > m) flag = 1;
while (tt > 0 && st[tt] == a[idx]) tt --, idx ++;
tt ++;
}
if (tt > 1 || flag) puts("NO");
else puts("YES");
}
return 0;
}
使用STL:
#include <iostream>
#include <stack>
using namespace std;
int m, n, k, a[1110];
int main(){
scanf("%d %d %d", &m, &n, &k);
while (k --){
stack<int> st;
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
int idx = 1;
bool flag = false;
for (int i = 1; i <= n; i++){
st.push(i);
if (st.size() > m) flag = true;
while (!st.empty() && st.top() == a[idx])
st.pop(),idx ++;
}
if (st.size() || flag) puts("NO");
else puts("YES");
}
return 0;
}