結果
問題 |
No.872 All Tree Path
|
ユーザー |
![]() |
提出日時 | 2019-10-14 15:34:01 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 691 ms / 3,000 ms |
コード長 | 1,356 bytes |
コンパイル時間 | 892 ms |
コンパイル使用メモリ | 81,664 KB |
実行使用メモリ | 155,776 KB |
最終ジャッジ日時 | 2024-12-24 01:34:24 |
合計ジャッジ時間 | 8,568 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 18 |
ソースコード
# nadare様のコード参考 # https://yukicoder.me/submissions/374115 N = int(input()) T = [[] for i in range(N)] E = [] for i in range(N - 1): a, b, w = map(int, input().split()) a, b = a - 1, b - 1 T[a].append(b) T[b].append(a) E.append([a, b, w]) class TwoDividedTree: def __init__(self, n, tree): self.tree = tree self.depth = [-1] * n self.size = [1] * n self.calc() def calc(self): self.depth[0] = 0 stack = [0] rev_directions = [] # 深いところから根に辿る辺の集合 while stack: fr = stack.pop() for to in self.tree[fr]: if self.depth[to] != -1: continue self.depth[to] = self.depth[fr] + 1 stack.append(to) rev_directions.append([fr, to]) while rev_directions: parent, child = rev_directions.pop() self.size[parent] += self.size[child] ''' 辺(a, b) で木を2分割した時の、片方のサイズ ''' def size_after_divided(self, a, b): if self.depth[a] < self.depth[b]: a, b = b, a return self.size[a] tdt = TwoDividedTree(N, T) ans = 0 for a, b, w in E: s = tdt.size_after_divided(a, b) ans += 2 * s * (N - s) * w print(ans)