UVA-514Rails(栈)

来源:互联网 发布:php url传递参数 编辑:程序博客网 时间:2024/04/30 02:04

题目来源:https://vjudge.net/problem/UVA-514

题意:某城市有一个火车站,有n节车厢从A方向驶入车站,按进站顺序编号为1~n。判断是否能让他们按照某种特定的顺序进入B方向并驶出车站。(只有A->C、C->B两种行驶选择)。

分析:在中转站C中,符合后进先出的规则,所以是一个栈。

参考代码:

#include<cstdio>#include<cmath>#include<cstdlib>#include<cctype>#include<cstring>#include<string>#include<sstream>#include<algorithm>#include<stack>#include<queue>#include<vector>#include<set>#include<map>#include<iostream>using namespace std;const int maxn = 1000+10;int n;int a[maxn];int main(){    while( ~scanf("%d",&n) && n)    {        while( true)        {            scanf("%d",&a[1]);            if( a[1] == 0)                break;            for( int i = 2; i <= n; i++)                scanf("%d",&a[i]);            stack<int> s;            int p = 1;//进栈的~            int q = 1;//下标            int flag = 1;            while( q <= n)//保证下标的合理性            {                if( p == a[q])//当前进栈的**和当前数组第q个相等                {                    p++;                    q++;                }                else if( !s.empty() && s.top() == a[q])//栈不空并且栈尾元素等于第p个元素                {                    s.pop();                    q++;                }                else if( p <= n)                    s.push(p++);                else                {                    flag = 0;                    break;                }            }            if( flag)                printf("Yes\n");            else                printf("No\n");        }        putchar(10);    }    return 0;}


0 0