输入规范说明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
我们以出栈序列元素为研究对象,一个一个判断之。先看出栈序列中第一个元素,第一个元素出栈,意味着小于它的整数曾经都已经入栈 ,也就是说出栈序列中下一个已出栈元素其值必然不小于栈顶元素(小于的都还在栈里面,不可能出栈了)所以不满足这个条件的出栈序列排除之;下一个已出栈元素其值大于栈顶元素,就让小于它的整数继续入栈,如果超出栈的容量大小,也排除之。如果所有元素都满足我们的要求,那么这个出栈序列就是正确的。
#includeusing namespace std; int main() { int M,N,K; cin>>M>>N>>K; int input; int j; int arr[1000];//用来存放随机出栈序列 //有K个需要判断的随机出栈序列 for(int i=0;i >input; arr[i]=input; } //初始化一个堆栈 int stack[1000]; int top=-1; //栈中第一个元素设置为1 int num=1; stack[++top]=num; //用来检查出栈序列中的每一个元素 for(j=0;j stack[top]) { stack[++top]=++num; } if(top>=M) break; if(stack[top]==arr[j]) top--;//注意此时num的值是没有减少的,意味着小于下次入栈元素的整数不包括已经出栈的数 //应对出栈序列是栈底的情况 if(top<0) stack[++top]=++num; } if(j==N) cout<<"YES"<



