Rails(判断出栈顺序是否合理)

来源:互联网 发布:机锋淘宝认证店靠谱吗? 编辑:程序博客网 时间:2024/06/06 06:49

Description

There is a famous railway station in PopPush City. Country there is incredibly hilly. The station was built in last century. Unfortunately, funds were extremely limited that time. It was possible to establish only a surface track. Moreover, it turned out that the station could be only a dead-end one (see picture) and due to lack of available space it could have only one track.
The local tradition is that every train arriving from the direction A continues in the direction B with coaches reorganized in some way. Assume that the train arriving from the direction A has N <= 1000 coaches numbered in increasing order 1, 2, ..., N. The chief for train reorganizations must know whether it is possible to marshal coaches continuing in the direction B so that their order will be a1, a2, ..., aN. Help him and write a program that decides whether it is possible to get the required order of coaches. You can assume that single coaches can be disconnected from the train before they enter the station and that they can move themselves until they are on the track in the direction B. You can also suppose that at any time there can be located as many coaches as necessary in the station. But once a coach has entered the station it cannot return to the track in the direction A and also once it has left the station in the direction B it cannot return back to the station.

题目描述

    小城PopPush有一个著名的火车站。这里地形起伏,丘陵绵延不断。这个站台建于上个世纪。不幸的是,那时的经费非常的紧缺,所以只能修建一条地表轨道。并且,由于空间限制,这条轨道只能是死胡同样式的。
    当地的传统是每辆火车都从A方向进来,然后车厢由某种方式重新组合后从B方向驶出。假设有一辆由N节车厢(N<=1000)的火车从A方向进来,每节车厢的编号为1,2,3…N。列车长必须知道火车车厢是否能以a1,a2…,aN的顺序从B方向驶出。请你写一个程序帮助他决定是否能得到他要求的驶出顺序。你可以假设单节车厢能在火车进站前分离,并且它们能自己移动到B方向的轨道。你也可以认为在任何时间你需要多少节车厢就会有多少节车厢。但是一旦这节车厢进入车站就不能再按A方向回去。而且一旦车厢离开车站进入B方向的轨道,就不能再回到车站。

图示:


输入和输出

输入包含多组数据。每组数据第一行为一个整数N,表示该列火车有N节车厢。下面的每一行中都有一个包含1到N的序列。每组测试数据的最后一行为一个整数0。最后一组测试数据只包含一个0。
输出结果的每一行与输入的序列相对应。如果输入的序列可以由初始的顺序整理得到,则输出Yes,否则输出No。每组测试数据的输出之间空一行。另外,最后一组为0的数据不对应任何输出。


AC代码:

#include <iostream>#include <stdio.h>#include <stack>using namespace std;int main(){    stack <int> st;    int i,j,n,a[1000];    while(scanf("%d",&n),n)    {        while(scanf("%d",&a[0]),a[0])        {            for(i=1;i<n;i++)                scanf("%d",&a[i]);            for(i=1,j=0;i<=n;i++)            {                st.push(i);                while(st.top()==a[j])                {                    st.pop();                    j++;                    if(st.empty())                        break;                }            }            if(j==n)                printf("Yes\n");            else                printf("No\n");        }        printf("\n");    }    return 0;}

 stl栈stack介绍

C++ Stack(堆栈) 是一个容器类的改编,为程序员提供了堆栈的全部功能,——也就是说实现了一个先进后出(FILO)的数据结构。

c++ stl栈stack的头文件为

#include <stack> 

c++ stl栈stack的成员函数介绍

操作 比较和分配堆栈

empty()堆栈为空则返回真

pop()移除栈顶元素

push()在栈顶增加元素

size()返回栈中元素数目

top()返回栈顶元素