问题描述
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.
输入规范说明
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.
输出规范说明
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
算法思想图解
我们以出栈序列元素为研究对象,一个一个判断之。先看出栈序列中第一个元素,第一个元素出栈,意味着小于它的整数曾经都已经入栈 ,也就是说出栈序列中下一个已出栈元素其值必然不小于栈顶元素(小于的都还在栈里面,不可能出栈了)所以不满足这个条件的出栈序列排除之;下一个已出栈元素其值大于栈顶元素,就让小于它的整数继续入栈,如果超出栈的容量大小,也排除之。如果所有元素都满足我们的要求,那么这个出栈序列就是正确的。