【PAT甲】1051 Pop Sequence (25分)判断出栈顺序的合法性

时间:2023-02-08 21:02:33


problem

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

  • 给定一个大小为n的栈,按照1,2,3,…n的顺序依次入栈
  • 给出k个长为m的出栈序列,判断是否合法

solution

直观的思路就是将入栈序列一个一个入栈,与出栈序列相比较,一样就出栈,不一样就继续入栈,当入栈序列和出栈序列都为空时,表示出栈顺序合法。

建立一个辅助栈 把输入的第一个序列中的数字一个一个压入该辅助栈,并按照第二个序列的顺序从该栈中弹出数字。
(1)如果元素是栈顶的元素,则pop出来;
(2)如果不是栈顶元素,则根据入栈顺序将没入栈的元素push进栈,直到将该元素push栈中,然后将该元素pop出来;如果push完所有元素都没有找到该元素,那么这个出栈顺序是错误的。最后辅助栈为空栈,并且遍历完了出栈序列的最后一个元素(二者缺一不可),那么该序列就是 一个弹出序列

#include<iostream>
#include<stack>
using namespace std;
int a[1010];

int main(){
int n, m, k;
cin>>n>>m>>k;
while(k--){
for(int i = 1; i <= m; i++)cin>>a[i];
int ok = 1, cur = 0;
stack<int>s;
for(int i = 1; i <= m; i++){
if(s.empty())s.push(++cur);
while(s.top()!=a[i]&&s.size()<=n)s.push(++cur);
if(s.size()>n){
ok = 0; break;
}
if(s.top()==a[i]){
s.pop(); continue;
}else{
ok = 0; break;
}
}
if(ok==1&&s.size()==0){
cout<<"YES\n";
}else{
cout<<"NO\n";
}
}
return 0;
}