結果

問題 No.872 All Tree Path
コンテスト
ユーザー koheijkt
提出日時 2026-01-12 18:35:15
言語 PyPy3
(7.3.17)
結果
AC  
実行時間 1,372 ms / 3,000 ms
コード長 2,683 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 463 ms
コンパイル使用メモリ 82,948 KB
実行使用メモリ 374,236 KB
最終ジャッジ日時 2026-01-12 18:35:28
合計ジャッジ時間 10,167 ms
ジャッジサーバーID
(参考情報)
judge4 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 18
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

import sys, math
import pypyjit
pypyjit.set_param('max_unroll_recursion=-1')
sys.setrecursionlimit(10**8)
sys.set_int_max_str_digits(0)
INF = 1e18
MOD = 998244353
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict, Counter
from itertools import product, combinations, permutations, groupby, accumulate
from heapq import heapify, heappop, heappush
def I():   return sys.stdin.readline().rstrip()
def II():  return int(sys.stdin.readline().rstrip())
def IS():  return sys.stdin.readline().rstrip().split()
def MII(): return map(int, sys.stdin.readline().rstrip().split())
def LI():  return list(sys.stdin.readline().rstrip())
def TII(): return tuple(map(int, sys.stdin.readline().rstrip().split()))
def LII(): return list(map(int, sys.stdin.readline().rstrip().split()))
def LSI(): return list(map(str, sys.stdin.readline().rstrip().split()))
def GMI(): return list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))
def kiriage(a, b): return (a+b-1)//b
def chmax(DP,i,v):
    if DP[i] < v: DP[i] = v
def chmin(DP,i,v):
    if DP[i] > v: DP[i] = v

N = II()
G = [list() for _ in range(N + 1)]
for i in range(N - 1):
    u, v, w = map(int, input().split())
    G[u].append((v, w))
    G[v].append((u, w))

# DP[pos]:= pos を根とする部分木において、根から全頂点への最短距離の合計
DP = [0] * (N + 1)
size = [1] * (N + 1)

def dfs1(pos, pre):
    for nex, w in G[pos]:
        if nex == pre:
            continue
        dfs1(nex, pos)
        # 戻ったときに、子どもの数を計上
        size[pos] += size[nex]
        # 最短距離の合計、その子どもまでの距離(×人数分)を計上
        DP[pos] += DP[nex] + w * size[nex]
    return

dfs1(1, 0)

# DP2[pos]:= pos を根とした時の根付き木の答え
# それらの合計がこの問題の求める答え
DP2 = [0] * (N + 1)

def dfs2(pos, pre):
    # 根において答えの計算
    DP2[pos] = DP[pos]

    for nex, w in G[pos]:
        # 無限ループさせないため、元来た方には移動しない
        if nex == pre:
            continue
        # 根の移動

        # 設定をバックアップ
        memo1, memo2, memo3, memo4 = DP[pos], DP[nex], size[pos], size[nex]

        # DP調整(sizeを使うのでsize調整より先に)
        DP[pos] -= DP[nex] + w*size[nex]
        # size調整
        size[pos] -= size[nex]
        size[nex] = N # 次根になる

        DP[nex] += DP[pos] + w*size[pos]
        dfs2(nex, pos)

        # 設定をリストア
        DP[pos], DP[nex], size[pos], size[nex] = memo1, memo2, memo3, memo4

    return

dfs2(1, 0)
ans = sum(DP2)
print(ans)
0