알고리즘
MST
by 이재현9999
2024. 10. 11.
import sys
input = sys.stdin.readline
def findParent(parent, x):
if parent[x] != x:
parent[x] = findParent(parent, parent[x])
return parent[x]
def unionParent(parent, a, b):
a = findParent(parent, a)
b = findParent(parent, b)
if a < b:
parent[b] = a
else:
parent[a] = b
V, E = map(int, input().split())
parent = [0] * (V + 1)
edges = []
result = 0
for i in range(1, V + 1):
parent[i] = i
for _ in range(E):
a, b, cost = map(int, input().split())
edges.append((cost, a, b))
edges.sort()
lst = []
for edge in edges:
cost, a, b = edge
if findParent(parent, a) != findParent(parent, b):
unionParent(parent, a, b)
lst.append(cost)
result += cost
print(result - max(lst))