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:
Sample Output:
栈里面经典例题:已知入栈顺序,判断所给序列是否可能是合法的出栈顺序
本题主要注意一下两点:
1.N出栈了 则其后面比N小的数字必须降序
<N 后出栈 则必然先进栈 又限制了进栈升序 那么出栈一定是降序了
(写代码时维护一个当前最大元素值即可)
2.不能爆栈
比如 容量5 入栈7 7出栈前至少两个出栈 7前面至少2个数字 也即7下标至少2(>=2) 其中2=7-5
算法笔记上给的解法是:
按顺序入栈,所给序列从头开始,一旦入栈数字等于序列头元素,入完立刻出栈,(删除序列头元素)。就直接模拟,直到发生矛盾:爆栈或者序列头元素已经入栈却不在栈顶。需要用栈模拟,也比较麻烦。。。