結果

問題 No.1254 補強への架け橋
ユーザー fukafukatanifukafukatani
提出日時 2020-10-09 22:51:00
言語 Rust
(1.83.0 + proconio)
結果
AC  
実行時間 131 ms / 2,000 ms
コード長 5,396 bytes
コンパイル時間 13,605 ms
コンパイル使用メモリ 379,424 KB
実行使用メモリ 58,820 KB
最終ジャッジ日時 2024-07-20 13:18:48
合計ジャッジ時間 24,303 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 123
権限があれば一括ダウンロードができます
コンパイルメッセージ
warning: unused variable: `i`
  --> src/main.rs:22:9
   |
22 |     for i in 0..n {
   |         ^ help: if this is intentional, prefix it with an underscore: `_i`
   |
   = note: `#[warn(unused_variables)]` on by default

warning: fields `from` and `to` are never read
   --> src/main.rs:158:5
    |
157 | struct Edge {
    |        ---- fields in this struct
158 |     from: usize,
    |     ^^^^
159 |     to: usize,
    |     ^^
    |
    = note: `Edge` has derived impls for the traits `Clone` and `Debug`, but these are intentionally ignored during dead code analysis
    = note: `#[warn(dead_code)]` on by default

ソースコード

diff #

#![allow(unused_imports)]
use std::cmp::*;
use std::collections::*;
use std::io::Write;
use std::ops::Bound::*;

#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), std::io::stderr());
            writeln!(err, "{} = {:?}", e, $e).unwrap()
        })*
    };
}

fn main() {
    let n = read::<usize>();

    let mut pairs = vec![];
    for i in 0..n {
        let v = read_vec::<usize>();
        let (a, b) = (v[0] - 1, v[1] - 1);
        pairs.push((a, b));
    }
    let mut uft = UnionFindTree::new(n);
    let mut not_used = 0;
    for i in 0..n {
        let (a, b) = pairs[i];
        if uft.same(a, b) {
            not_used = i;
            break;
        }
        uft.unite(a, b);
    }

    let mut tree = vec![vec![]; n];
    for i in 0..n {
        if i == not_used {
            continue;
        }
        let (a, b) = pairs[i];
        tree[a].push(b);
        tree[b].push(a);
    }

    let lca = LCA::new(&tree);
    let (a, b) = pairs[not_used];
    let lca_node = lca.lca(a, b);

    let mut answers = vec![(a, b)];

    for &start in &[a, b] {
        let mut cur = start;
        while cur != lca_node {
            let parent = lca.parent[0][cur].unwrap();
            answers.push((cur, parent));
            cur = parent;
        }
    }
    // debug!(answers);

    let mut index_map = HashMap::new();
    for i in 0..n {
        let (u, v) = pairs[i];
        index_map.insert((u, v), i);
        index_map.insert((v, u), i);
    }

    println!("{}", answers.len());
    for (u, v) in answers {
        print!("{} ", index_map[&(u, v)] + 1);
    }
    println!("");
}

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

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

struct LCA {
    depth: Vec<usize>,
    parent: Vec<Vec<Option<usize>>>,
    log_v: usize,
}

impl LCA {
    fn new(g: &Vec<Vec<usize>>) -> LCA {
        LCA::with_root(g, 0)
    }

    fn with_root(g: &Vec<Vec<usize>>, root: usize) -> LCA {
        let n = g.len();
        let log_v = (1..).find(|i| 1usize << i > n).unwrap();
        let mut lca = LCA {
            depth: vec![0usize; n],
            parent: vec![vec![None; n]; 18 + 1], // support 2 ^ 20
            log_v: log_v,
        };
        lca.dfs(root, None, 0, &g);
        lca.doubling(g.len());
        lca
    }

    fn doubling(&mut self, n: usize) {
        for k in 0..self.log_v {
            for v in 0..n {
                if let Some(parent_v) = self.parent[k][v] {
                    self.parent[k + 1][v] = self.parent[k][parent_v];
                }
            }
        }
    }

    fn dfs(&mut self, cur: usize, p: Option<usize>, cur_depth: usize, g: &Vec<Vec<usize>>) {
        self.parent[0][cur] = p;
        self.depth[cur] = cur_depth;
        for &to in g[cur].iter() {
            if Some(to) == p {
                continue;
            }
            self.dfs(to, Some(cur), cur_depth + 1, g);
        }
    }

    fn lca(&self, mut u: usize, mut v: usize) -> usize {
        if self.depth[u] > self.depth[v] {
            std::mem::swap(&mut u, &mut v);
        }
        while self.depth[v] != self.depth[u] {
            v = self.parent[(self.depth[v] - self.depth[u]).trailing_zeros() as usize][v].unwrap();
        }
        if u == v {
            return u;
        }
        for k in (0..self.parent.len()).rev() {
            if self.parent[k][u] != self.parent[k][v] {
                u = self.parent[k][u].unwrap();
                v = self.parent[k][v].unwrap();
            }
        }
        self.parent[0][u].unwrap()
    }
}

#[derive(Debug, Clone)]
struct Edge {
    from: usize,
    to: usize,
    cost: i32,
}

impl PartialEq for Edge {
    fn eq(&self, other: &Edge) -> bool {
        self.cost == other.cost
    }
}

impl Eq for Edge {}

impl Ord for Edge {
    fn cmp(&self, other: &Self) -> Ordering {
        self.cost.cmp(&other.cost)
    }
}

impl PartialOrd for Edge {
    fn partial_cmp(&self, other: &Edge) -> Option<Ordering> {
        Some(self.cost.cmp(&other.cost))
    }
}

struct UnionFindTree {
    parent_or_size: Vec<isize>,
}

impl UnionFindTree {
    fn new(size: usize) -> UnionFindTree {
        UnionFindTree {
            parent_or_size: vec![-1; size],
        }
    }

    fn find(&self, index: usize) -> usize {
        let mut index = index;
        while self.parent_or_size[index] >= 0 {
            index = self.parent_or_size[index] as usize;
        }
        index
    }

    fn same(&self, x: usize, y: usize) -> bool {
        self.find(x) == self.find(y)
    }

    fn unite(&mut self, index0: usize, index1: usize) -> bool {
        let a = self.find(index0);
        let b = self.find(index1);
        if a == b {
            false
        } else {
            if self.parent_or_size[a] < self.parent_or_size[b] {
                self.parent_or_size[a] += self.parent_or_size[b];
                self.parent_or_size[b] = a as isize;
            } else {
                self.parent_or_size[b] += self.parent_or_size[a];
                self.parent_or_size[a] = b as isize;
            }
            true
        }
    }
}
0