POJ 1363

Rails


Input

The input consists of blocks of lines. Each block except the last describes one train and possibly more requirements for its reorganization. In the first line of the block there is the integer N described above. In each of the next lines of the block there is a permutation of 1, 2, ..., N. The last line of the block contains just 0. 

The last block consists of just one line containing 0.

Output

The output contains the lines corresponding to the lines with permutations in the input. A line of the output contains Yes if it is possible to marshal the coaches in the order required on the corresponding line of the input. Otherwise it contains No. In addition, there is one empty line after the lines corresponding to one block of the input. There is no line in the output corresponding to the last ``null'' block of the input.

Sample Input

5
1 2 3 4 5
5 4 1 2 3
0
6
6 5 4 3 2 1
0
0

Sample Output

Yes
No

Yes
这道题是判断出栈顺序是否合法。。。
代码如下:
#include<cstdio>
#include<stack>
#include<cstring>
#include<cstdlib>
using namespace std;
int main()
{
    int i,n;
    int m,flag;
    while(scanf("%d",&n),n)
    {
        flag=0;
        while(!flag)
        {
            stack <int> s;//把对栈S的定义放在循环外面,可减去每次的输出都要复原的麻烦。
            int t=1;
            s.push(t);//把t=1作为栈顶元素插入
            for(i=1;i<=n;i++)//输入待判断的出栈顺序
            {   
                scanf("%d",&m);
                
                if(m==0)//当输入的出栈顺序为‘0’时,表示对出栈顺序的输入结束//
                {
                    flag=1;
                    break;
                }
                if(s.empty())//如果栈为空,就入栈,
                {
                    t++;
                    s.push(t);
                }
                int top=s.top();
                while(top!=m)//当栈顶元素与输出元素不相同时,比出栈的值小的数就入栈,直到栈顶元素与出栈的值相同。
                {
                    if(t==n)
                       break;
                       t++;
                    s.push(t);
                    top=s.top();//更新栈顶元素
                }
                if(top==m)//当栈顶元素与出栈元素相同时,删除S的栈顶元素。
                    s.pop();
            }
            if(flag)//如果输入为‘0’,表示全部输入结束
                break;
            if(s.empty())//如果栈为空,说明每次删除的栈顶元素与输入的出栈顺序相同,即‘Yes’,否则‘No’。
                puts("Yes");
            else
                puts("No");
        }
        printf("\n");
    }
    getchar(); //
    return 0;
}
栈是限定只能在表的栈顶进行插入和删除操作的线性表。。。
栈的修改原则后进先出。。。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值