Rails (UVA - 514)

版权声明:欢迎转载!拒绝抄袭. https://blog.csdn.net/qq_36257146/article/details/87714137

UVa514 Rails(铁轨)
题目:铁轨
题目链接:UVa514链接
题目描述:
某城市有一个火车站,有n节车厢从A方向驶入车站,按进站的顺序编号为1-n.你的任务是判断是否能让它们按照某种特定的顺序进入B方向的铁轨并驶入车站。例如,出栈顺序(5 4 1 2 3)是不可能的,但是(5 4 3 2 1)是可能的。
题目分析:
为了重组车厢,借助中转站,对于每个车厢,一旦从A移入C就不能回到A了,一旦从C移入B,就不能回到C了,意思就是A->C和C->B。而且在中转站C中,车厢符合后进先出的原则。故这里可以看做为一个栈。


#include <iostream>
#include <bits/stdc++.h>
#define maxn 1000+10
using namespace std;
int target[maxn];

int main()
{
    int n;
    while(cin>>n&&n!=0)
    {
        while(cin>>target[1] && target[1])
        {
            int A = 1,B = 1;
            stack<int>s;
            for(int i = 2;i<=n;i++)
                cin>>target[i];
            while(B<=n)
            {
                if(target[B]==A)
                {
                    A++;B++;
                }
                else if(!s.empty()&&s.top() == target[B])
                {
                    s.pop();
                    B++;
                }
                else if(A<=n)
                {
                    s.push(A++);
                }
                else
                    break;
            }
            if(B<=n)
                cout<<"No"<<endl;
            else
                cout<<"Yes"<<endl;
        }
        cout<<endl;
    }
    return 0;
}
/**
5
1 2 3 4 5
5 4 1 2 3
0
6
6 5 4 3 2 1
0
0
**/

猜你喜欢

转载自blog.csdn.net/qq_36257146/article/details/87714137