栈-铁轨(uva514)

首先梳理一下关于栈的知识:

头文件:
#include<stack>//栈
定义方式:
stack<int>  s;//参数也是数据类型,这是栈的定义方式
基本操作:
s.empty()//如果栈为空返回true,否则返回false  
s.size()//返回栈中元素的个数  
s.pop()//删除栈顶元素但不返回其值  
s.top()//返回栈顶的元素,但不删除该元素  
s.push(X)//在栈顶压入新元素 ,参数X为要压入的元素

Uva 铁轨(栈)514

Input

The input file 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 file contains the lines corresponding to the lines with permutations in the input file. A line of the output file contains ‘Yes’ if it is possible to marshal the coaches in the order required on the correspondinglineoftheinputfile. Otherwiseitcontains‘No’. Inaddition, thereisoneemptylineafter the lines corresponding to one block of the input file. There is no line in the output file corresponding to the last “null” block of the input file.

5
1 2 3 4 5
5 4 1 2 3
0
6
6 5 4 3 2 1
0 
0
输入
Yes
No

Yes
输出

在任意时刻,只能A->C,和C->B,也就是说那个序列的子序列要么是顺序的,要么是倒序的。

紫书上的思路非常精妙

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stack>
using namespace std;
#define maxn 1050
int target[maxn];
int main()
{
    int n;
    while(scanf("%d", &n)==1&&n)
    {
        while(scanf("%d", &target[1]),target[1])
        {
            for(int i=2; i<=n; i++)
                scanf("%d", &target[i]);
                stack<int> st;
                int A = 1, B = 1;
                int ok = 1;
                while(B<=n)
                {
                    if(A==target[B]){A++; B++;}
                    else if(!st.empty()&&st.top()==target[B])
                    {
                        B++;
                        st.pop();
                    }
                    else if(A<=n)
                        st.push(A++);
                    else
                    {
                        ok = 0;
                        break;
                    }
                }
                printf("%s\n", ok?"Yes":"No");
        }
        printf("\n");
    }
    return 0;
}

(1)如果子序列是顺序的,第一个if就能解决,如果出现倒序子序列,则入栈,然后出栈。

(2)还有就是格式的问题。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值