栈的应用——Rails

一、题目描述

某城市有一个火车站,有n节车厢从A方向驶入车站,按进站顺序编号为1~n,经中转站C驶向B。中转站C,这是一个可以停放任意多节车厢的车站,但由于末端封顶,驶入C的车厢必须以相反的顺序驶出C。你的任务是判断它能否按某种顺序进入B方向的车站。

二、解题思路

中转站C就相当于一个栈,可以随时入栈和出栈。

三、代码实现

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<stack>
 4 #include<cstdbool>
 5 using namespace std;
 6 
 7 const int maxn = 100 + 10;
 8 int n, target[maxn];
 9 
10 int main()
11 {
12     while (scanf("%d",&n) == 1)
13     {
14         stack<int>s;
15         int A = 1, B = 1;
16         for (int i = 1; i <= n; i++)
17             scanf("%d", &target[i]);
18 
19         bool ok = true;
20         while (B <= n)
21         {
22             if (A == target[B]){        //从A中取
23                 A++, B++; 
24             }
25             else if (!s.empty() && s.top() == target[B]) { //从栈中取
26                 s.pop();
27                 B++;
28             }
29             else if (A <= n)  s.push(A++);        //栈顶不是目标元素,从A入栈
30             else {                            //都不是,说明不可能
31                 ok = false;
32                 break;
33             }
34         }
35         printf("%s\n", ok ? "Yes" : "No");
36     }
37     return 0;
38 }

 

转载于:https://www.cnblogs.com/lfri/p/9459324.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值