본문 바로가기
알고리즘

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))

'알고리즘' 카테고리의 다른 글

Divide and Conquer Square  (0) 2024.10.14
Sieve of Eratosthenes  (1) 2024.10.11
Prefix Sum, Prefix Sum of Matrix  (0) 2024.10.11
Topology Sort  (0) 2024.10.11
Segment Tree  (0) 2024.10.11