최소 신장 트리(Minimum Spanning Tree, MST)를 찾는 대표적인 알고리즘 중 하나인 크루스칼 알고리즘은 그리디 알고리즘(Greedy Algorithm)을 기반으로 설계되었습니다. 이 알고리즘은 간선(Edge)을 하나씩 추가하면서 MST를 구성합니다.
# Union-Find 구현
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x]) # 경로 압축
return self.parent[x]
def union(self, x, y):
root_x = self.find(x)
root_y = self.find(y)
if root_x != root_y:
if self.rank[root_x] > self.rank[root_y]:
self.parent[root_y] = root_x
elif self.rank[root_x] < self.rank[root_y]:
self.parent[root_x] = root_y
else:
self.parent[root_y] = root_x
self.rank[root_x] += 1
def kruskal(n, edges):
edges.sort(key=lambda x: x[2]) # 간선을 가중치 기준으로 정렬
uf = UnionFind(n)
mst = []
total_weight = 0
for u, v, weight in edges:
if uf.find(u) != uf.find(v):
uf.union(u, v)
mst.append((u, v, weight))
total_weight += weight
return mst, total_weight
# 그래프 정의 (정점 수, 간선 리스트)
n = 4
edges = [
(0, 1, 10),
(0, 2, 6),
(0, 3, 5),
(1, 3, 15),
(2, 3, 4)
]
mst, total_weight = kruskal(n, edges)
print("MST:", mst)
print("Total Weight:", total_weight)
위 코드에서 그래프는 다음과 같이 표현됩니다:
출력 예시는 다음과 같습니다:
MST: [(2, 3, 4), (0, 3, 5), (0, 1, 10)]
Total Weight: 19