結果

問題 No.872 All Tree Path
ユーザー 双六
提出日時 2020-07-22 15:59:42
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
AC  
実行時間 1,415 ms / 3,000 ms
コード長 1,465 bytes
コンパイル時間 319 ms
コンパイル使用メモリ 12,800 KB
実行使用メモリ 117,708 KB
最終ジャッジ日時 2024-06-12 00:54:53
合計ジャッジ時間 13,424 ms
ジャッジサーバーID
(参考情報)
judge4 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 18
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
from collections import deque
INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

class BFS(object):
	def __init__(self, graph, s, N):
		self.g = graph.graph
		self.Q = deque(); self.Q.append(s)
		self.dist = [INF] * N; self.dist[s] = 0
		self.prev = [None] * N; self.prev[s] = -1
		while self.Q:
			v = self.Q.popleft()
			for i in self.g[v]:
				if self.dist[i] == INF:
					self.dist[i] = self.dist[v] + 1
					self.prev[i] = v
					self.Q.append(i)

def DFS(G, W, visit, node):
	for i in G.graph[node]:
		if visit[i] != 1:
			visit[i] = 1
			DFS(G, W, visit, i)
			W[node] += W[i]

#処理内容
def main():
	N = int(input())
	G = Graph()
	edge = defaultdict(int)
	for i in range(N - 1):
		a, b, w = getlist()
		a, b = list(sorted([a, b]))
		a -= 1; b -= 1
		edge[a * (10 ** 6) + b] = w
		G.add_edge(a, b)
		G.add_edge(b, a)

	#DFS
	W = [1] * N
	visit = [0] * N
	visit[0] = 1
	DFS(G, W, visit, 0)

	# print(W)

	BF = BFS(G, 0, N)

	ans = 0
	for i in range(1, N):
		p = BF.prev[i]; q = i
		weight = W[q] * (N - W[q])
		p, q = list(sorted([p, q]))
		w = edge[p * (10 ** 6) + q]
		ans += weight * w

	print(ans * 2)



if __name__ == '__main__':
	main()
0