結果

問題 No.1418 Sum of Sum of Subtree Size
ユーザー phspls
提出日時 2022-11-10 00:06:23
言語 Rust
(1.83.0 + proconio)
結果
AC  
実行時間 70 ms / 2,000 ms
コード長 1,000 bytes
コンパイル時間 12,790 ms
コンパイル使用メモリ 400,496 KB
実行使用メモリ 21,984 KB
最終ジャッジ日時 2024-07-23 04:53:04
合計ジャッジ時間 14,757 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 41
権限があれば一括ダウンロードができます

ソースコード

diff #

fn dfs(cur: usize, prev: usize, paths: &Vec<Vec<(usize, usize)>>, cnts: &mut Vec<usize>) -> usize {
    let mut ret = 1usize;
    for &(v, idx) in paths[cur].iter() {
        if v == prev { continue; }
        let val = dfs(v, cur, paths, cnts);
        ret += val;
        cnts[idx] = val;
    }
    ret
}

fn main() {
    let mut n = String::new();
    std::io::stdin().read_line(&mut n).ok();
    let n: usize = n.trim().parse().unwrap();
    let mut paths = vec![vec![]; n];
    for i in 0..n-1 {
        let mut ab = String::new();
        std::io::stdin().read_line(&mut ab).ok();
        let ab: Vec<usize> = ab.trim().split_whitespace().map(|s| s.parse().unwrap()).collect();
        let a = ab[0]-1;
        let b = ab[1]-1;
        paths[a].push((b, i));
        paths[b].push((a, i));
    }

    let mut cnts = vec![0usize; n-1];
    dfs(0, 0, &paths, &mut cnts);
    let mut result = n*n;
    for &v in cnts.iter() {
        result += (n - v) * v * 2;
    }
    println!("{}", result);
}
0