結果

問題 No.872 All Tree Path
ユーザー AT274_AT274_
提出日時 2019-10-14 15:34:01
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 562 ms / 3,000 ms
コード長 1,356 bytes
コンパイル時間 276 ms
コンパイル使用メモリ 87,236 KB
実行使用メモリ 158,440 KB
最終ジャッジ日時 2023-08-25 16:41:05
合計ジャッジ時間 6,879 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 562 ms
157,936 KB
testcase_01 AC 541 ms
154,624 KB
testcase_02 AC 522 ms
158,440 KB
testcase_03 AC 286 ms
144,840 KB
testcase_04 AC 61 ms
71,180 KB
testcase_05 AC 484 ms
158,080 KB
testcase_06 AC 491 ms
157,768 KB
testcase_07 AC 507 ms
154,904 KB
testcase_08 AC 126 ms
84,148 KB
testcase_09 AC 128 ms
84,196 KB
testcase_10 AC 135 ms
84,332 KB
testcase_11 AC 139 ms
84,428 KB
testcase_12 AC 139 ms
84,708 KB
testcase_13 AC 66 ms
71,556 KB
testcase_14 AC 65 ms
71,208 KB
testcase_15 AC 66 ms
71,228 KB
testcase_16 AC 65 ms
71,416 KB
testcase_17 AC 70 ms
71,148 KB
testcase_18 AC 71 ms
71,316 KB
testcase_19 AC 65 ms
71,156 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

# 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)
0