铁轨(栈的逻辑运用)

某城有一火车站,有n节车厢从A方向驶入车站,按进站顺序为1~n,要求:让它按照某种特定顺序进入B方向的铁轨并驶出车站。其中有一个中转站C,用来重组车厢。

A有俩种方式出站,一是借助中转站C,这涉及到栈的问题,二是直接从B出去。所以要判断出站顺序就只要判断B出站的车厢在此时的A与以C作为中转站的栈的栈顶是否存在就行。

所以要求将1到n顺序添加,如果能够满足B出站车厢直接出栈,否则进栈,若A中不存在车厢了,而且栈顶无法匹配此时B出站的车厢就错误了!注意逻辑转换!!!

#include<iostream>
#include<cstdio>
#include<string>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=1005;
int main()
{
    int n;
    int flag=1;
    while(cin>>n)
    {
        if(flag>1) cout<<endl;
        if(n==0)  break;
        int x[maxn];
        cin>>x[1];

        while(x[1]!=0)
        {
            for(int i=2;i<=n;i++)
                cin>>x[i];
            int A=1,B=1;
            stack <int >s;
            int ok=1;
            while(B<=n)
            {
                if(A==x[B]) {A++;B++;}
                else if(!s.empty()&&s.top()==x[B]) {s.pop();B++;}
                else if(A<=n) {s.push(A++);}
                else
                {
                   ok=0;
                   break;
                    }
}
            printf("%s
",ok ?"Yes":"No");
            flag++;
            cin>>x[1];
 }
}
 return 0;
}

  

原文地址:https://www.cnblogs.com/blvt/p/7199437.html