PAT甲级1051
原题:
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
题目大意:给出栈容量,1~n个元素,待查的序列个数,判断给出的序列是否是合法的出栈序列
注意点:
1、每趟判断结束要清空栈!
2、边输入序列边判断,若是发现不合法不能直接break,可以立个flag标记,之后可以不做任何处理,但一定要继续把剩下数字读完!
#include <iostream>
#include <stack>
using namespace std;
int main(){
int m,n,k;
scanf("%d%d%d",&m,&n,&k);
stack<int> s;
for(int j=0;j<k;j++){
int min=1; //min记录下次进栈开始的数
bool flag=true; //记录是否是一个合法的出栈序列
for(int i=0;i<n;i++){
int t;
scanf("%d",&t);
if(flag){
if(s.empty()||t>s.top()){ //若栈为空或者数字比栈顶元素大则进栈
for(int l=min;l<=t;l++) s.push(l);
min=t+1; //下次进栈从t+1开始
if(s.size()>m){ //若进栈的数量大于栈容量
flag=false;
}
}
if(t==s.top()) s.pop();
else if(t<s.top()){ //若出栈的数字不是栈顶则出错
flag=false;
}
}
}
if(flag) printf("YES\n");
else printf("NO\n");
while(!s.empty()) s.pop(); //清空栈
}
system("pause");
return 0;
}