結果

問題 No.1103 Directed Length Sum
ユーザー StrorkisStrorkis
提出日時 2020-07-03 22:57:56
言語 Rust
(1.72.1)
結果
AC  
実行時間 591 ms / 3,000 ms
コード長 1,463 bytes
コンパイル時間 869 ms
コンパイル使用メモリ 173,144 KB
実行使用メモリ 182,496 KB
最終ジャッジ日時 2023-10-17 06:00:27
合計ジャッジ時間 6,981 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,348 KB
testcase_01 AC 1 ms
4,348 KB
testcase_02 AC 332 ms
182,496 KB
testcase_03 AC 138 ms
41,888 KB
testcase_04 AC 324 ms
29,452 KB
testcase_05 AC 591 ms
49,508 KB
testcase_06 AC 199 ms
19,888 KB
testcase_07 AC 35 ms
6,100 KB
testcase_08 AC 61 ms
8,424 KB
testcase_09 AC 19 ms
4,516 KB
testcase_10 AC 86 ms
10,812 KB
testcase_11 AC 355 ms
31,828 KB
testcase_12 AC 199 ms
19,888 KB
testcase_13 AC 90 ms
11,068 KB
testcase_14 AC 14 ms
4,348 KB
testcase_15 AC 151 ms
15,996 KB
testcase_16 AC 396 ms
35,720 KB
testcase_17 AC 421 ms
37,040 KB
testcase_18 AC 90 ms
10,784 KB
testcase_19 AC 370 ms
32,620 KB
testcase_20 AC 26 ms
5,044 KB
testcase_21 AC 53 ms
7,880 KB
testcase_22 AC 286 ms
26,880 KB
testcase_23 AC 167 ms
16,984 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

struct DFS {
    graph: Vec<Vec<usize>>,
}

impl DFS {
    const MOD: usize = 1_000_000_007;

    fn new(n: usize) -> DFS {
        DFS {
            graph: vec![vec![]; n],
        }
    }

    fn add_edge(&mut self, from: usize, to: usize) {
        self.graph[from].push(to);
    }

    fn search(&mut self, from: usize, d: usize) -> usize {
        let mut res = 0;
        for &to in self.graph[from].clone().iter() {
            res += self.search(to, d + 1);
        }
        (res + (1 + d) * d / 2) % Self::MOD
    }
}

fn main() {
    let n: usize = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        buf.trim_end().parse().unwrap()
    };

    let mut dfs = DFS::new(n);
    let mut is_root = vec![true; n];
    for _ in 0..(n - 1) {
        let (a, b): (usize, usize) = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            let mut iter = buf.split_whitespace();
            (
                iter.next().unwrap().parse::<usize>().unwrap() - 1,
                iter.next().unwrap().parse::<usize>().unwrap() - 1,
            )
        };
        dfs.add_edge(a, b);
        is_root[b] = false;
    }

    let root = {
        is_root.iter()
            .enumerate()
            .filter(|&(_, &b)| b)
            .map(|(i, _)| i)
            .next()
            .unwrap()
    };

    let ans = dfs.search(root, 0);
    println!("{}", ans);
}
0