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:

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出栈了  则其后面比N小的数字必须降序 
          <N 后出栈 则必然先进栈    又限制了进栈升序  那么出栈一定是降序了
          (写代码时维护一个当前最大元素值即可)     
    
        2.不能爆栈  
            比如 容量5 入栈7  7出栈前至少两个出栈  7前面至少2个数字  也即7下标至少2(>=2) 其中2=7-5 

#include<bits/stdc++.h>
using namespace std;
int m,n,k;//容量 push个数 k查询次数
int a[1010],Max;
string ans;
int main(){
// freopen("in.txt","r",stdin);
cin>>m>>n>>k;
while(k--){
Max=0;ans="YES";
for(int i=0;i<n;i++) scanf("%d",a+i);
for(int i=0;i<n;i++){
if(i>0&&a[i]<Max&&a[i-1]<Max&&a[i-1]<a[i]){
ans="NO";
break;
}else if(a[i]>m&&i<a[i]-m){
ans="NO";
break;
}else if(a[i]>Max){
Max=a[i];//维护最大值 其后小于他的必然都降序
}
}
printf("%s\n",ans.c_str());
}
return 0;
}

算法笔记上给的解法是:

1051 Pop Sequence (25 分)  栈_出栈

按顺序入栈,所给序列从头开始,一旦入栈数字等于序列头元素,入完立刻出栈,(删除序列头元素)。就直接模拟,直到发生矛盾:爆栈或者序列头元素已经入栈却不在栈顶。需要用栈模拟,也比较麻烦。。。