結果

問題 No.872 All Tree Path
ユーザー 双六双六
提出日時 2020-07-22 15:59:42
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 1,313 ms / 3,000 ms
コード長 1,465 bytes
コンパイル時間 353 ms
コンパイル使用メモリ 10,880 KB
実行使用メモリ 115,264 KB
最終ジャッジ日時 2023-09-02 18:26:30
合計ジャッジ時間 12,315 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1,313 ms
77,352 KB
testcase_01 AC 1,289 ms
76,556 KB
testcase_02 AC 1,296 ms
80,188 KB
testcase_03 AC 883 ms
115,264 KB
testcase_04 AC 19 ms
8,656 KB
testcase_05 AC 1,277 ms
76,456 KB
testcase_06 AC 1,270 ms
79,204 KB
testcase_07 AC 1,271 ms
76,480 KB
testcase_08 AC 100 ms
14,512 KB
testcase_09 AC 101 ms
14,536 KB
testcase_10 AC 99 ms
14,340 KB
testcase_11 AC 100 ms
14,376 KB
testcase_12 AC 99 ms
14,544 KB
testcase_13 AC 19 ms
8,800 KB
testcase_14 AC 18 ms
8,812 KB
testcase_15 AC 19 ms
8,796 KB
testcase_16 AC 19 ms
8,804 KB
testcase_17 AC 18 ms
8,668 KB
testcase_18 AC 18 ms
8,668 KB
testcase_19 AC 18 ms
8,860 KB
権限があれば一括ダウンロードができます

ソースコード

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