铁轨

来源:互联网 发布:申请手机淘宝账号注册 编辑:程序博客网 时间:2024/03/28 19:18

某城市有一个铁轨,有n节车厢从A方向驶入车站,你可以借助一个中转站C,驶入C中的车厢必须按照相反的顺序驶出C,在任意时刻只有两种选择:A->C  ,C->B。

#include <iostream>using namespace std;const int MAX=1000+10;int main(){    int n;    while(cin>>n)    {        if(n==1)        return 0;        int stack[MAX];        int target[MAX];        int top=1;        int A=1;        int B=1;        for(int i=1;i<=n;i++)        {            cin>>target[i];        }        int ok=1;        while(B<=n)        {            if(A==target[B])            {                A++;                B++;            }            else if(top&&stack[top]==target[B])            {                top--;                B++;            }            else if(A<=n)            {                stack[++top]=A++;            }            else            {                ok=0;                break;            }        }      if(ok==1)        cout<<"YES"<<endl;     else            cout<<"NO"<<endl;      }    return 0;}

5
1 2 3 4 5
YES


5
5 4 1 2 3
NO


6
1 2 3 4 5 6
YES

原创粉丝点击