結果

問題 No.872 All Tree Path
ユーザー terasaterasa
提出日時 2022-06-01 22:45:07
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,334 ms / 3,000 ms
コード長 973 bytes
コンパイル時間 303 ms
コンパイル使用メモリ 81,464 KB
実行使用メモリ 373,980 KB
最終ジャッジ日時 2023-10-21 00:59:52
合計ジャッジ時間 12,123 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 904 ms
145,852 KB
testcase_01 AC 902 ms
145,900 KB
testcase_02 AC 1,334 ms
146,576 KB
testcase_03 AC 998 ms
373,980 KB
testcase_04 AC 49 ms
55,516 KB
testcase_05 AC 972 ms
146,292 KB
testcase_06 AC 923 ms
146,160 KB
testcase_07 AC 967 ms
145,828 KB
testcase_08 AC 152 ms
83,512 KB
testcase_09 AC 136 ms
83,296 KB
testcase_10 AC 131 ms
83,180 KB
testcase_11 AC 144 ms
83,324 KB
testcase_12 AC 150 ms
83,352 KB
testcase_13 AC 44 ms
55,516 KB
testcase_14 AC 46 ms
55,516 KB
testcase_15 AC 44 ms
55,516 KB
testcase_16 AC 44 ms
55,516 KB
testcase_17 AC 44 ms
55,516 KB
testcase_18 AC 44 ms
55,516 KB
testcase_19 AC 45 ms
55,516 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
import pypyjit
import itertools
import heapq
import math
from collections import deque, defaultdict
import bisect

input = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)
pypyjit.set_param('max_unroll_recursion=-1')


N = int(input())
adj = [{} for _ in range(N)]
for _ in range(N - 1):
    u, v, w = map(int, input().split())
    u -= 1
    v -= 1
    adj[u][v] = w
    adj[v][u] = w

child = [None] * N
cost = [None] * N
cost[0] = 0


def dfs(v, p):
    if v > 0:
        cost[v] = cost[p] + adj[v][p]
    acc = 1
    for d in adj[v].keys():
        if d == p:
            continue
        acc += dfs(d, v)
    child[v] = acc
    return child[v]


dfs(0, -1)
S = sum(cost)
ans = 0


def dfs2(v, p):
    global ans, S
    if v > 0:
        S += adj[v][p] * (N - 2 * child[v])
    ans += S
    for d in adj[v].keys():
        if d == p:
            continue
        dfs2(d, v)
    if v > 0:
        S -= adj[v][p] * (N - 2 * child[v])


dfs2(0, -1)
print(ans)
0