# 도시 분할 계획 - BOJ

도시 분할 계획 - BOJ

  • union-find 및 크루스칼 알고리즘 활용하여 풀이
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

N, M = map(int, input().split())
parent = [0] * (N + 1)
edges = []
ret = 0

for i in range(1, N + 1):
    parent[i] = i

for _ in range(M):
    A, B, C = map(int, input().split())
    edges.append((C, A, B))

edges.sort()
biggest = 0

for edge in edges:
    C, A, B = edge
    if find(parent, A) != find(parent, B):
        union(parent, A, B)
        ret += C
        biggest = C
print(ret - biggest)