結果

問題 No.872 All Tree Path
ユーザー FromBooska
提出日時 2023-08-30 21:25:29
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,310 ms / 3,000 ms
コード長 1,002 bytes
コンパイル時間 421 ms
コンパイル使用メモリ 82,476 KB
実行使用メモリ 424,556 KB
最終ジャッジ日時 2025-01-02 18:30:09
合計ジャッジ時間 13,525 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 18
権限があれば一括ダウンロードができます

ソースコード

diff #

N = int(input())
edge_list = []
edge_dic = {}
edges = [[] for i in range(N+1)]
for i in range(N-1):
    u, v, w = map(int, input().split())
    edges[u].append(v)
    edges[v].append(u)
    edge_list.append((u, v, w))
    edge_dic[(u, v)] = w
    edge_dic[(v, u)] = w

child = [0]*(N+1)
visited = [0]*(N+1)

import sys
sys.setrecursionlimit(10**7)

def dfs(current):
    visited[current] = 1
    child[current] += 1
    
    for nxt in edges[current]:
        if visited[nxt] == 0:
            dfs(nxt)
            child[current] += child[nxt]

for i in range(1, N+1):
    if len(edges[i]) == 1:
        root = i
        break
            
dfs(root)
#print(child)

def dfs2(current, prev):
    global ans
    for nxt in edges[current]:
        if nxt != prev:
            #print('current', current, 'nxt', nxt, child[nxt], (N-child[nxt]), edge_dic[(current, nxt)])
            ans += child[nxt]*(N-child[nxt])*edge_dic[(current, nxt)]
            dfs2(nxt, current)

ans = 0
dfs2(root, 0)
print(ans*2)
0