UVa514 Rails

题目:

有n节车厢从A方向驶入车站,按进站顺序编号为1~n.

判断是否能让它们按照某种特定的顺序进入B方向的铁轨并驶出车站。

分析:

在中转站Station中,车厢符合后进先出的原则,因此是一个栈。代码如下:

#include<cstdio>
#include<stack>
using namespace std;
const int MAXN=1010;

int n,target[MAXN];

int main(){
    while(scanf("%d",&n)==1){
        stack<int> s;
        int A=1,B=1;
        for(int i=1;i<=n;i++)
            scanf("%d",&target[i]);
        int ok=1;
        while(B<=n){
            if(A==target[B]){
                A++;
                B++;
            }
            else if(!s.empty()&&s.top()==target[B]){
                s.pop();
                B++;
            }
            else if(A<=n){
                s.push(A++);
            }
            else{
                ok=0;
                break;
            }
        }
        printf("%s
",ok?"Yes":"No");
    }
    return 0;
} 
原文地址:https://www.cnblogs.com/hellosnow/p/6424739.html