1seul357
[SWEA] 최소 신장 트리 본문
def Find(x):
if P[x] != x:
P[x] = Find(P[x])
return P[x]
def Union(a, b):
pa = Find(a)
pb = Find(b)
P[pb] = pa
T = int(input())
for TC in range(T):
N, M = map(int, input().split())
P = [i for i in range(N+1)]
edges = []
ans = 0
for i in range(M):
n1, n2, w = map(int, input().split())
edges.append((w, n1, n2))
edges.sort()
for w, n1, n2 in edges:
if Find(n1) == Find(n2):
continue
Union(n1, n2)
ans += w
print('#{} {}'.format(TC+1, ans))
'알고리즘 > SWEA' 카테고리의 다른 글
[SWEA] 이진수 (0) | 2021.11.28 |
---|---|
[SWEA] 최장 경로 (0) | 2021.11.28 |
[SWEA] 최소비용 (0) | 2021.11.28 |
[SWEA] 창용 마을 무리의 개수 (0) | 2021.11.28 |
[SWEA] 보급로 (0) | 2021.11.28 |