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、等待入栈的最大值n(入栈序列1,2,3,4,5,6.....n)以及需要检查序列的个数k。判断给定序列是否是出栈的序列。
思路:
本来我的思路是从输出的序列着手,设置一定的条件不满足的就输出NO。可是后来写出来之后的不了满分,我的思路出现了漏洞,左思右想得不出结论,求助网友。看到网友的代码简洁,思路清晰,是模仿堆栈的入栈,弹栈的过程,佩服啊。再一次感谢网友。
代码:
#include <iostream>
using namespace std;
int main(int argc,const char*argv[]){
int m,n,k;
cin>>m>>n>>k;
int stack[1005];
for(int i=0;i<k;i++){
int number;
int top=0;
int flag=1;
int now=1;
for(int j=0;j<n;j++){
cin>>number;
while(flag&&(top==0||stack[top]!=number)){
stack[++top]=now;
if(top>m){
flag=0;
break;
}
now++;
}
if(flag&&top>=1&&stack[top]==number){
top--;
}
}
if(flag){
cout<<"YES"<<endl;
}else{
cout<<"NO"<<endl;
}
}
return 0;
}