結果

問題 No.1103 Directed Length Sum
ユーザー yuly3yuly3
提出日時 2020-07-27 23:50:33
言語 PyPy3
(7.3.15)
結果
MLE  
実行時間 -
コード長 1,346 bytes
コンパイル時間 1,596 ms
コンパイル使用メモリ 86,968 KB
実行使用メモリ 832,212 KB
最終ジャッジ日時 2023-09-11 06:09:40
合計ジャッジ時間 5,526 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 72 ms
71,252 KB
testcase_01 AC 73 ms
71,288 KB
testcase_02 MLE -
testcase_03 -- -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


class TreeDP:
    def __init__(self, graph, merge, add_root, ide_ele):
        self.graph = graph
        self.merge = merge
        self.add_root = add_root
        self.ide_ele = ide_ele
        self.dp = [ide_ele] * len(graph)
        self.depth = [0] * len(graph)
    
    def dfs(self, cur, parent=-1):
        dp_cum = self.ide_ele
        if parent != -1:
            self.depth[cur] = self.depth[parent] + 1
        for child in self.graph[cur]:
            if child == parent:
                continue
            dp_cum = self.merge(dp_cum, self.dfs(child, cur))
        self.dp[cur] = self.add_root(dp_cum)
        return self.dp[cur]


def solve():
    MOD = 10 ** 9 + 7
    N = int(rl())
    graph = [[] for _ in range(N)]
    r = {u for u in range(N)}
    for _ in range(N - 1):
        a, b = map(lambda n: int(n) - 1, rl().split())
        graph[a].append(b)
        r.remove(b)
    
    merge = lambda n, m: n + m
    add_root = lambda n: n + 1
    tree_dp = TreeDP(graph, merge, add_root, 0)

    root = list(r)[0]
    tree_dp.dfs(root)
    ans = 0
    for parent in range(N):
        for child in graph[parent]:
            ans += (tree_dp.depth[parent] + 1) * tree_dp.dp[child]
            ans %= MOD
    print(ans)


if __name__ == '__main__':
    solve()
0