栈的应用——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 }

猜你喜欢

转载自www.cnblogs.com/lfri/p/9459324.html
今日推荐