結果

問題 No.1333 Squared Sum
ユーザー akakimidoriakakimidori
提出日時 2021-01-22 15:22:34
言語 Rust
(1.83.0 + proconio)
結果
AC  
実行時間 396 ms / 2,000 ms
コード長 1,515 bytes
コンパイル時間 18,049 ms
コンパイル使用メモリ 379,760 KB
実行使用メモリ 34,704 KB
最終ジャッジ日時 2024-12-26 15:56:11
合計ジャッジ時間 28,562 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 44
権限があれば一括ダウンロードができます

ソースコード

diff #

fn main() {
    let (n, e) = {
        use std::io::Read;
        let mut s = String::new();
        std::io::stdin().read_to_string(&mut s).unwrap();
        let mut it = s.trim().split_whitespace();
        let n: usize = it.next().unwrap().parse().unwrap();
        let e: Vec<(usize, usize, u64)> = (1..n).map(|_| {
            let a = it.next().unwrap().parse::<usize>().unwrap() - 1;
            let b = it.next().unwrap().parse::<usize>().unwrap() - 1;
            let c = it.next().unwrap().parse::<u64>().unwrap();
            (a, b, c)
        }).collect();
        (n, e)
    };
    let mut g = vec![vec![]; n];
    for (a, b, c) in e {
        g[a].push((b, c));
        g[b].push((a, c));
    }
    let mut topo = vec![0];
    for i in 0..n {
        let v = topo[i];
        for (u, _) in g[v].clone() {
            let x = g[u].iter().position(|p| p.0 == v).unwrap();
            g[u].remove(x);
            topo.push(u);
        }
    }
    const MOD: u64 = 1_000_000_007;
    let mut ans = 0;
    let mut dp = vec![(0, 0, 0); n];
    for &v in topo.iter().rev() {
        let mut val = (0, 0, 1);// w^2, w, cnt
        for (u, w) in std::mem::take(&mut g[v]) {
            let (a, b, c) = dp[u];
            let (a, b) = ((w * w % MOD * c + 2 * w * b + a) % MOD, (b + c * w) % MOD);
            ans += (a * val.2 + val.0 * c + 2 * val.1 * b) % MOD;
            val = ((val.0 + a) % MOD, (val.1 + b) % MOD, val.2 + c);
        }
        dp[v] = val;
    }
    ans %= MOD;
    println!("{}", ans);
}
0