A1051 Pop Sequence (25point(s))
题意
给定栈的最大长度,给出k个序列,进栈的顺序是1到n,输出这个序列是否是合法的出栈序列。
思路
直接模拟。
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
#include"bits/stdc++.h"
using namespace std;
int main() {
// freopen("input.txt","r",stdin);
int n,m,k;
cin >> m >> n >> k;
list<int> a;
for(int i=1; i<=n; i++) a.push_front(i);
for(int i=0; i<k; i++) {
bool ok = true;
stack<int> s;
list<int> at = a;
for(int j=0;j<n;j++){
int v; scanf("%d",&v);
if(!ok) continue;
while(!at.empty() && v >= at.back()){
s.push(at.back());
if(s.size() > m) {
ok = false;
break;
}
at.pop_back();
}
if(!ok) continue;
ok = false;
while(!s.empty()){
if(s.top() == v){
ok = true;
s.pop();
break;
}
s.pop();
}
}
if(!ok)
printf("NO\n");
else
printf("YES\n");
}
}