import heapq
def prim(n, graph):
visited = set()
pq = [(0, 0)]
mst_cost = 0
while pq:
weight, node = heapq.heappop(pq)
if node in visited:
continue
visited.add(node)
mst_cost += weight
for neighbor, w in graph[node]:
if neighbor not in visited:
heapq.heappush(pq, (w, neighbor))
return mst_cost
graph = {0: [(1, 1), (2, 4)], 1: [(0, 1), (2, 2)], 2: [(0, 4), (1, 2)]}
print(prim(3, graph))
'코테 > Algorithm & 방식' 카테고리의 다른 글
[Algorithm] 세그먼트 트리 (0) | 2025.03.20 |
---|---|
[Algorithm] 위상 정렬 (0) | 2024.03.22 |
[Algorithm] Kruskal (0) | 2024.03.22 |
[Algorithm] 서로소 집합 알고리즘 (0) | 2024.03.22 |
[Algorithm] 플로이드 워셜 (0) | 2024.03.22 |