結果

問題 No.1103 Directed Length Sum
ユーザー phspls
提出日時 2020-07-07 20:18:05
言語 Rust
(1.83.0 + proconio)
結果
AC  
実行時間 1,362 ms / 3,000 ms
コード長 1,962 bytes
コンパイル時間 15,458 ms
コンパイル使用メモリ 404,264 KB
実行使用メモリ 240,964 KB
最終ジャッジ日時 2024-10-01 18:57:40
合計ジャッジ時間 27,127 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 22
権限があれば一括ダウンロードができます

ソースコード

diff #

use std::collections::{VecDeque, HashSet};

const DIVISOR: usize = 1_000_000_007;

fn dfs(path: &mut Vec<VecDeque<usize>>, index: usize, result: &mut VecDeque<usize>, checked: &mut HashSet<usize>) {
    if checked.contains(&index) { return; }
    while let Some(next) = path[index].pop_front() {
        dfs(path, next, result, checked);
    }
    checked.insert(index);
    result.push_front(index);
}

fn topological_sort(path: &mut Vec<VecDeque<usize>>) -> VecDeque<usize> {
    let mut result: VecDeque<usize> = VecDeque::new();
    let mut checked: HashSet<usize> = HashSet::new();
    let limit = path.len();
    for i in 0..limit {
        dfs(path, i, &mut result, &mut checked);
    }
    result
}

fn calc(path: &mut Vec<VecDeque<usize>>, index: usize, depth: &mut usize) -> usize {
    if path[index].is_empty() { return *depth * (*depth + 1) / 2 % DIVISOR; }
    let mut flg = false;
    let mut result: usize = 0;
    while let Some(next) = path[index].pop_front() {
        *depth += 1;
        let val = calc(path, next, depth);
        *depth -= 1;
        result += val;
        if !flg {
            result += *depth * (*depth + 1) / 2;
            flg = true;
        }
        result %= DIVISOR;
    }
    result % DIVISOR
}

fn main() {
    let mut n = String::new();
    std::io::stdin().read_line(&mut n).ok();
    let n: usize = n.trim().parse().unwrap();
    let mut path: Vec<VecDeque<usize>> = vec![VecDeque::new(); n];
    for _ 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::<usize>().unwrap() - 1usize).collect();
        path[ab[0]].push_back(ab[1]);
    }
    let mut path_data = path.clone();
    let mut sorted_indices = topological_sort(&mut path);
    let parent = sorted_indices.pop_front().unwrap();
    
    let mut depth: usize = 0;
    println!("{}", calc(&mut path_data, parent, &mut depth));
}
0