結果

問題 No.1418 Sum of Sum of Subtree Size
ユーザー phspls
提出日時 2022-12-06 21:23:49
言語 Rust
(1.83.0 + proconio)
結果
AC  
実行時間 61 ms / 2,000 ms
コード長 1,066 bytes
コンパイル時間 12,918 ms
コンパイル使用メモリ 378,888 KB
実行使用メモリ 22,016 KB
最終ジャッジ日時 2024-10-13 09:17:14
合計ジャッジ時間 16,439 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
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, qidx) in paths[cur].iter() {
        if v == prev { continue; }
        let val = dfs(v, cur, paths, cnts);
        cnts[qidx] = val;
        ret += 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 temp = String::new();
        std::io::stdin().read_line(&mut temp).ok();
        let temp: Vec<usize> = temp.trim().split_whitespace().map(|s| s.parse().unwrap()).collect();
        let a = temp[0]-1;
        let b = temp[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() {
        let left = v;
        let right = n - v;
        result += 2 * left * right;
    }
    println!("{}", result);
}
0