铁轨(Rails, ACM/ICPC CERC 1997, UVa 514)rust解法

有一个火车站,铁轨铺设如图6-1所示。有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中,车厢符合后进先出的原则,因此是一个栈。

样例:

输入

复制代码
5
5 4 3 2 1

输出

复制代码
yes

解法:

rust 复制代码
use std::{collections::VecDeque, io};

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let n: usize = buf.trim().parse().unwrap();
    let mut source = VecDeque::from((1..=n).collect::<Vec<_>>());
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let target: Vec<usize> = buf.split_whitespace().map(|x| x.parse().unwrap()).collect();
    let mut b = 0;
    let mut s: VecDeque<usize> = VecDeque::new();
    while b < n {
        if !source.is_empty() && *source.front().unwrap() == target[b] {
            source.pop_front();
            b += 1;
        } else if !s.is_empty() && *s.back().unwrap() == target[b] {
            s.pop_back();
            b += 1;
        } else if !source.is_empty() {
            s.push_back(source.pop_front().unwrap());
        } else {
            break;
        }
    }
    if b == n {
        println!("yes");
    } else {
        println!("no");
    }
}
相关推荐
DongLi018 小时前
rustlings 学习笔记 -- exercises/05_vecs
rust
番茄灭世神1 天前
Rust学习笔记第2篇
rust·编程语言
shimly1234561 天前
(done) 速通 rustlings(20) 错误处理1 --- 不涉及Traits
rust
shimly1234561 天前
(done) 速通 rustlings(19) Option
rust
@atweiwei1 天前
rust所有权机制详解
开发语言·数据结构·后端·rust·内存·所有权
shimly1234561 天前
(done) 速通 rustlings(24) 错误处理2 --- 涉及Traits
rust
shimly1234561 天前
(done) 速通 rustlings(23) 特性 Traits
rust
shimly1234561 天前
(done) 速通 rustlings(17) 哈希表
rust
shimly1234561 天前
(done) 速通 rustlings(15) 字符串
rust
shimly1234561 天前
(done) 速通 rustlings(22) 泛型
rust