Loading

算法竞赛入门经典 例题6-2 铁轨(C、python)

同个人网站 https://www.serendipper-x.cn/,欢迎访问 !

问题描述:
某城市有一个火车站,铁轨铺设如图所示。有n节车厢从A方向驶入车站,按进站顺序编号为 1~n 。你的任务是判断是否能让它们按照某种特定的顺序进入 B 方向的铁轨并驶出车站。例如,出栈顺序(5 4 1 2 3)是不可能的,但(5 4 3 2 1)是可能的。

为了重组车厢,你可以借助中转站 C。这是一个可以停放任意多节车厢的车站,但由于末端封顶,驶入 C 的车厢必须按照相反的顺序驶出 C。对于每个车厢,一旦从 A 移入 C ,就不能再回到 A 了;一旦从 C 移入 B,就不能回到 C 了。换句话说,在任意时刻,只能由两种选择: A -> C 和 C -> B。
在这里插入图片描述

分析: 在这里中转站 C 符合先进后出的原则,可以把它当作是

C:

#include<cstdio>
#include<stack>
using namespace std;
const int MAXN = 1000 + 10;

int n, target[MAXN];

int main(){
	while(scanf("%d", &n) == 1){
		stack<int> s;
		int A = 1, B = 1;
		for(int i = 1; i <= n; i++)
			scanf("%d", &target[i]);
		int ok = 1;
		while(B <= n){
			if(A == target[B]){
				A++;B++;
			}
			else if(!s.empty() && s.top() == target[B]){
				s.pop();B++;
			}
			else if(A <= n)
				s.push(A++);
			else{
				ok = 0;
				break;
			}
		}
		printf("%s\n", ok ? "Yes" : "No");
	}
	return 0;
}

Python:

n = int(input())
target = list(map(int, input().split()))  # 测试队列
stack = []

ok, A, B = 1, 1, 0
while B < n:
    if A == target[B]:
        A += 1
        B += 1
    elif len(stack) != 0 and stack[len(stack)-1] == target[B]:
        stack.pop()
        B += 1
    elif A <= n:
        stack.append(A)
        A += 1
    else:
        ok = 0
        break
if ok == 1:
    print ("Yes")
else:
    print ("No")
posted @ 2021-02-19 16:03  XiaoJ_c  阅读(83)  评论(0编辑  收藏  举报