AtCoder Beginner Contest 429 E

https://atcoder.jp/contests/abc429/tasks/abc429_e

各点でSの点までの距離を求めればよいです。ただし、異なる2つのSの点を求めなければなりません。

// Hit and Away
#![allow(non_snake_case)]


//////////////////// library ////////////////////

fn read<T: std::str::FromStr>() -> T {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).ok();
    line.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>().split_whitespace()
            .map(|e| e.parse().ok().unwrap()).collect()
}


//////////////////// Graph ////////////////////

type Node = usize;
type Edge = (Node, Node);

fn read_edge() -> Edge {
    let v: Vec<Node> = read_vec();
    (v[0]-1, v[1]-1)
}

const INF: i32 = 1000000;

struct Graph {
    g: Vec<Vec<Node>>,
    s: Vec<bool>,
    dists: Vec<[(i32, Node); 2]>
}

impl Graph {
    fn read() -> Graph {
        let v: Vec<usize> = read_vec();
        let (N, M) = (v[0], v[1]);
        let mut g: Vec<Vec<Node>> = vec![vec![]; N];
        for _ in 0..M {
            let (U, V) = read_edge();
            g[U].push(V);
            g[V].push(U)
        }
        let S: String = read();
        let s: Vec<bool> = S.chars().map(|c| c == 'S').collect();
        Graph { g, s, dists: vec![[(INF, N); 2]; N] }
    }
}


//////////////////// process ////////////////////

fn F(mut graph: Graph) {
    let N = graph.g.len();
    let mut w: Vec<Node> = vec![];
    for v in 0..N {
        if graph.s[v] {
            graph.dists[v][0] = (0, v);
            w.push(v)
        }
    }
    
    for d in 1.. {
        let mut new_w: Vec<Node> = vec![];
        for v0 in w {
            let [(d01, v01), (d02, v02)] = graph.dists[v0];
            let mut vs: Vec<Node> = vec![];     // 距離がdのSの点
            if d01 == d-1 {
                vs.push(v01)
            }
            if d02 == d-1 {
                vs.push(v02)
            }
            for &v in graph.g[v0].iter() {
                let [(d1, v1), (d2, _)] = graph.dists[v];
                let mut setting = false;
                for &v_src in vs.iter() {
                    if d1 == INF {
                        graph.dists[v][0] = (d, v_src);
                        setting = true
                    }
                    else if d2 == INF && v_src != v1 {
                        graph.dists[v][1] = (d, v_src);
                        setting = true
                    }
                }
                if setting {
                    new_w.push(v)
                }
            }
        }
        if new_w.is_empty() {
            break
        }
        w = new_w
    }
    
    for v in (0..N).filter(|&v| !graph.s[v]) {
        println!("{}", graph.dists[v][0].0 + graph.dists[v][1].0)
    }
}

fn main() {
    let graph = Graph::read();
    F(graph)
}