반응형
https://www.acmicpc.net/problem/1922
def find(parent, x):
if parent[x] != x:
parent[x] = find(parent, parent[x])
return parent[x]
def union(parent, a, b):
a = find(parent, a)
b = find(parent, b)
if a < b:
parent[b] = a
else:
parent[a] = b
import sys
n = int(input())
m = int(input())
parent = [0]*(n+1)
edges = []
result = 0
for i in range(n+1):
parent[i] = i
for _ in range(m):
a, b, cost = map(int, sys.stdin.readline().split())
edges.append([cost, a, b])
edges.sort()
for i in range(len(edges)):
cost, a, b = edges[i]
if find(parent, a) != find(parent, b):
union(parent, a, b)
result += cost
print(result)
댓글