线性结构 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.
输入样例:
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
输出样例:
YES
NO
NO
YES
NO
题解
判断出栈序列是否合法,可以用一个栈来模拟出栈顺序。先判断栈是否为空或栈顶元素是否与序列相等,空或者不相等则按照顺序将元素入栈,直到相等或已全部入栈。入栈时要判断栈满,栈满则不能入栈,序列非法。最后栈应该为空,不为空非法。
如序列3 2 1 7 5 6 4,一开始为3,栈空,按照顺序入栈,1,2,3,然后3出栈,2出栈,1出栈。到7,按照顺序入栈4,5,6,7,7出栈。到5与栈顶元素不同,且元素已全部入栈,栈非空,序列非法。
c代码
#include <stdio.h>
#include <stdlib.h>
int k, n, m;
int main() {
scanf("%d%d%d", &m, &n, &k);
int* stack = (int *)malloc(sizeof (int) * (m + 5));
int* sq = (int *)malloc(sizeof (int) * (n + 5));
while (k--) {
int top = -1;
for (int i = 1; i <= n; i++) scanf("%d", &sq[i]); //读入出栈序列
for (int i = 1, j = 1; i <= n; i++ ) {
stack[++top] = i; //按顺序入栈
if(top >= m) break; //栈满,非法
while(top != -1 && stack[top] == sq[j]) { //判断栈顶元素是否与序列相同
top--;
j++;
}
}
if(top == -1) puts("YES");
else puts("NO");
}
return 0;
}