【出栈顺序判断】 Rails

传送门

题意

多组样例,每次输入一个(N),表示栈的长度,等于0时候终止输入,然后每次输入(1sim N)的一个排列,判断能否通过(1sim N)的入栈顺序输出

数据范围

(1leq Nleq 1000)

题解

模拟入栈,只要当前栈顶等于给定的排列就一直出栈,最后判断栈是否为空及给定的排列是否取尽即可

Code

#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for(int i=a;i<n;i++)
#define close ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int n;
void solve(){
    int a[1010];
    while(cin>>a[1],a[1]){
        rep(i,2,n+1) 
            cin>>a[i];
        int stk[1010],tot=0;
        
        int j=1;
        rep(i,1,n+1){
            stk[++tot]=i;
            while(tot && stk[tot] == a[j])  
                tot--,j++;
        }
        cout<<((j==n+1 && tot==0)?"Yes
":"No
");
    }
    cout<<endl;
}
int main(){
    close
    while(cin>>n&&n) solve();
}

// 5
// 1 2 3 4 5
// 5 4 1 2 3
// 0
// 6 
// 6 5 4 3 2 1
// 0
// 0
原文地址:https://www.cnblogs.com/hhyx/p/13424466.html