結果

問題 No.922 東北きりきざむたん
ユーザー fukafukatanifukafukatani
提出日時 2019-11-09 17:43:04
言語 Rust
(1.77.0 + proconio)
結果
WA  
実行時間 -
コード長 7,176 bytes
コンパイル時間 16,005 ms
コンパイル使用メモリ 378,976 KB
実行使用メモリ 51,620 KB
最終ジャッジ日時 2024-09-15 04:39:58
合計ジャッジ時間 28,287 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
10,624 KB
testcase_01 AC 1 ms
5,248 KB
testcase_02 AC 1 ms
5,248 KB
testcase_03 AC 1 ms
5,376 KB
testcase_04 AC 1 ms
5,376 KB
testcase_05 AC 1 ms
5,376 KB
testcase_06 AC 1 ms
5,376 KB
testcase_07 AC 1 ms
5,376 KB
testcase_08 AC 1 ms
5,376 KB
testcase_09 WA -
testcase_10 WA -
testcase_11 WA -
testcase_12 AC 11 ms
7,040 KB
testcase_13 AC 8 ms
5,376 KB
testcase_14 WA -
testcase_15 AC 6 ms
6,784 KB
testcase_16 TLE -
testcase_17 WA -
testcase_18 WA -
testcase_19 WA -
testcase_20 WA -
testcase_21 TLE -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
testcase_27 -- -
testcase_28 -- -
testcase_29 -- -
権限があれば一括ダウンロードができます
コンパイルメッセージ
warning: function `make_tree` is never used
   --> src/main.rs:210:4
    |
210 | fn make_tree(
    |    ^^^^^^^^^
    |
    = note: `#[warn(dead_code)]` on by default

warning: function `topological_dfs` is never used
   --> src/main.rs:225:4
    |
225 | fn topological_dfs(cur_idx: usize, tree: &Vec<Vec<usize>>, result: &mut Vec<usize>) {
    |    ^^^^^^^^^^^^^^^

warning: method `get_size` is never used
   --> src/main.rs:262:8
    |
239 | impl UnionFindTree {
    | ------------------ method in this implementation
...
262 |     fn get_size(&mut self, x: usize) -> usize {
    |        ^^^^^^^^

ソースコード

diff #

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

#[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 v = read_vec::<usize>();
    let (n, m, q) = (v[0], v[1], v[2]);
    let mut edges = vec![vec![]; n];
    let mut uft = UnionFindTree::new(n);
    for _ in 0..m {
        let v = read_vec::<usize>();
        let (a, b) = (v[0] - 1, v[1] - 1);
        edges[a].push(b);
        edges[b].push(a);
        uft.unite(a, b);
    }
    let mut used = vec![0; n];
    let mut imos = vec![0; n];
    let mut same_pairs = HashMap::new();
    for _ in 0..q {
        let v = read_vec::<usize>();
        let (a, b) = (v[0] - 1, v[1] - 1);
        if uft.same(a, b) {
            same_pairs.entry(uft.find(a)).or_insert(vec![]).push((a, b));
        } else {
            used[a] += 1;
            used[b] += 1;
        }
    }

    let mut roots = HashSet::new();
    for i in 0..n {
        let root = uft.find(i);
        if edges[root].is_empty() {
            continue;
        }
        roots.insert(root);
    }
    let mut ans = 0;

    for &root in roots.iter() {
        if same_pairs.contains_key(&root) {
            let lca = LCA::with_root(root, &edges);
            for &(a, b) in same_pairs[&root].iter() {
                let ca = lca.lca(a, b);
                ans += (lca.depth[a] + lca.depth[b] - lca.depth[ca]) as i64;
            }
        }

        let mut sum_count = 0;
        dfs1(
            root,
            root,
            root,
            &edges,
            &used,
            0,
            &mut sum_count,
            &mut imos,
        );
        let mut min_cost = std::i64::MAX;
        dfs2(root, root, sum_count, &edges, &mut min_cost, &mut imos);
        ans += min_cost;
    }
    println!("{}", ans);
}

fn dfs1(
    cur: usize,
    parent: usize,
    root: usize,
    edges: &Vec<Vec<usize>>,
    used: &Vec<i64>,
    depth: i64,
    sum_count: &mut i64,
    imos: &mut Vec<i64>,
) -> i64 {
    *sum_count += used[cur];
    imos[root] += (depth * used[cur]) as i64;
    let mut k = used[cur];
    for &child in edges[cur].iter() {
        if child == parent {
            continue;
        }
        k += dfs1(child, cur, root, edges, used, depth + 1, sum_count, imos);
    }
    if cur != root {
        imos[cur] = -2 * k;
    }
    k
}

fn dfs2(
    cur: usize,
    parent: usize,
    sum_count: i64,
    edges: &Vec<Vec<usize>>,
    min_cost: &mut i64,
    imos: &mut Vec<i64>,
) {
    *min_cost = min(*min_cost, imos[cur]);
    for &child in edges[cur].iter() {
        if child == parent {
            continue;
        }
        imos[child] += sum_count + imos[cur];
        dfs2(child, cur, sum_count, edges, min_cost, imos);
    }
}

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

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

    pub fn with_root(root: usize, g: &[Vec<usize>]) -> LCA {
        fn dfs(
            i: usize,
            p: Option<usize>,
            d: usize,
            g: &[Vec<usize>],
            depth: &mut [usize],
            parent: &mut [Vec<Option<usize>>],
        ) {
            parent[i][0] = p;
            depth[i] = d;

            for &t in &g[i] {
                if Some(t) != p {
                    dfs(t, Some(i), d + 1, g, depth, parent);
                }
            }
        }
        let n = g.len();
        let l2 = (1..).find(|i| 1usize << i > n).unwrap();
        let mut depth = vec![0; n];
        let mut parent = vec![vec![None; l2 + 1]; n];

        dfs(root, None, 0, &g, &mut depth, &mut parent);

        for i in 1..l2 + 1 {
            for j in 0..n {
                if let Some(p) = parent[j][i - 1] {
                    parent[j][i] = parent[p][i - 1];
                }
            }
        }

        LCA {
            depth: depth,
            parent: parent,
        }
    }

    pub fn lca(&self, mut a: usize, mut b: usize) -> usize {
        use std::mem::swap;
        if self.depth[b] < self.depth[a] {
            swap(&mut a, &mut b);
        }

        while self.depth[a] != self.depth[b] {
            b = self.parent[b][(self.depth[b] - self.depth[a]).trailing_zeros() as usize].unwrap();
        }

        if a == b {
            return a;
        }

        for i in (0..self.parent[0].len()).rev() {
            if self.parent[a][i] != self.parent[b][i] {
                a = self.parent[a][i].unwrap();
                b = self.parent[b][i].unwrap();
            }
        }
        self.parent[a][0].unwrap()
    }
}

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()
}

fn make_tree(
    cur_idx: usize,
    parent_idx: usize,
    edges: &Vec<Vec<usize>>,
    tree: &mut Vec<Vec<usize>>,
) {
    for child_idx in edges[cur_idx].iter() {
        if *child_idx == parent_idx {
            continue;
        }
        tree[cur_idx].push(*child_idx);
        make_tree(*child_idx, cur_idx, edges, tree);
    }
}

fn topological_dfs(cur_idx: usize, tree: &Vec<Vec<usize>>, result: &mut Vec<usize>) {
    for child_idx in tree[cur_idx].iter() {
        result.push(*child_idx);
        topological_dfs(*child_idx, tree, result);
    }
}

#[derive(Debug, Clone)]
struct UnionFindTree {
    parent: Vec<isize>,
    size: Vec<usize>,
    height: Vec<u64>,
}

impl UnionFindTree {
    fn new(n: usize) -> UnionFindTree {
        UnionFindTree {
            parent: vec![-1; n],
            size: vec![1usize; n],
            height: vec![0u64; n],
        }
    }

    fn find(&mut self, index: usize) -> usize {
        if self.parent[index] == -1 {
            return index;
        }
        let idx = self.parent[index] as usize;
        let ret = self.find(idx);
        self.parent[index] = ret as isize;
        ret
    }

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

    fn get_size(&mut self, x: usize) -> usize {
        let idx = self.find(x);
        self.size[idx]
    }

    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.height[a] > self.height[b] {
                self.parent[b] = a as isize;
                self.size[a] += self.size[b];
            } else if self.height[a] < self.height[b] {
                self.parent[a] = b as isize;
                self.size[b] += self.size[a];
            } else {
                self.parent[b] = a as isize;
                self.size[a] += self.size[b];
                self.height[a] += 1;
            }
            true
        }
    }
}
0