PAT.A1051 Pop Sequence_入栈

题意

有个容量限制为m的栈,将1,2,3…n依次入栈,给出q个出栈顺序,问这些出栈顺序是否可能。

样例(可复制)

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
//output

注意点

  1. 注意入栈中途可以出栈
  2. 本题使用的STL的stack,常见的操作有st.pop()弹出栈顶,st.push()在栈顶插入,st.empty()返回栈是否为空,st.size()返回栈的大小,st.top()返回栈顶元素(不会弹出)
#include<bits/stdc++.h>
using namespace std;

int arr[1010];
stack<int> st;
int main(){
int m,n,q;//容量,入栈个数,查询次数
cin>>m>>n>>q;
while(q--){
while(!st.empty())st.pop();
for(int i=1;i<=n;i++)scanf("%d",&arr[i]);
int now=1,flag=1;
for(int i=1;i<=n;i++){
st.push(i);
if(st.size()>m){
flag=0;break;
}
while(!st.empty()&&st.top()==arr[now]){
st.pop();
now++;
}
}
if(st.empty()&&flag)printf("YES\n");
else printf("NO\n");
}
return 0;
}