結果

問題 No.872 All Tree Path
ユーザー toyuzukotoyuzuko
提出日時 2020-05-06 16:35:01
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 1,364 ms / 3,000 ms
コード長 1,672 bytes
コンパイル時間 100 ms
コンパイル使用メモリ 10,944 KB
実行使用メモリ 122,932 KB
最終ジャッジ日時 2023-09-11 03:40:42
合計ジャッジ時間 13,617 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1,355 ms
111,532 KB
testcase_01 AC 1,346 ms
110,816 KB
testcase_02 AC 1,364 ms
114,484 KB
testcase_03 AC 757 ms
122,932 KB
testcase_04 AC 16 ms
8,040 KB
testcase_05 AC 1,329 ms
110,824 KB
testcase_06 AC 1,332 ms
113,308 KB
testcase_07 AC 1,329 ms
110,524 KB
testcase_08 AC 113 ms
18,504 KB
testcase_09 AC 111 ms
18,500 KB
testcase_10 AC 114 ms
18,624 KB
testcase_11 AC 113 ms
18,492 KB
testcase_12 AC 115 ms
18,500 KB
testcase_13 AC 17 ms
8,108 KB
testcase_14 AC 17 ms
8,044 KB
testcase_15 AC 17 ms
8,108 KB
testcase_16 AC 16 ms
8,064 KB
testcase_17 AC 17 ms
8,232 KB
testcase_18 AC 16 ms
8,212 KB
testcase_19 AC 17 ms
8,220 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class Tree():
    def __init__(self, n, edge):
        self.n = n
        self.tree = [[] for _ in range(n)]
        for e in edge:
            self.tree[e[0] - 1].append((e[1] - 1, e[2]))
            self.tree[e[1] - 1].append((e[0] - 1, e[2]))

    def setroot(self, root):
        self.root = root
        self.parent = [None for _ in range(self.n)]
        self.parent[root] = -1
        self.depth = [None for _ in range(self.n)]
        self.depth[root] = 0
        self.distance = [None for _ in range(self.n)]
        self.distance[root] = 0
        self.order = []
        self.order.append(root)
        self.cost = [0 for _ in range(self.n)]
        self.size = [1 for _ in range(self.n)]
        stack = [root]
        while stack:
            node = stack.pop()
            for adj, cost in self.tree[node]:
                if self.parent[adj] is None:
                    self.parent[adj] = node
                    self.depth[adj] = self.depth[node] + 1
                    self.distance[adj] = self.distance[node] + cost
                    self.cost[adj] = cost
                    self.order.append(adj)
                    stack.append(adj)
        for node in self.order[::-1]:
            for adj, cost in self.tree[node]:
                if self.parent[node] == adj:
                    continue
                self.size[node] += self.size[adj]

import sys
input = sys.stdin.readline

N = int(input())
E = [tuple(map(int, input().split())) for _ in range(N - 1)]

tree = Tree(N, E)
tree.setroot(0)

res = 0

for node in range(N):
    if node == 0:
        continue
    res += tree.cost[node] * tree.size[node] * (N - tree.size[node]) * 2

print(res)
0