BOJ - 1922 - 네트워크 연결

Updated:

import sys
import heapq

def PRIM(graph, V, idx):
    hq = []
    visit = [False] * (V + 1)
    visit[idx] = True
    distance = 0
    cnt = 1

    for i in graph[idx]:
        heapq.heappush(hq, i)

    while hq:
        weight, vertex = heapq.heappop(hq)
        if not visit[vertex]:
            visit[vertex] = True
            cnt += 1
            distance += weight
            for i in graph[vertex]:
                heapq.heappush(hq, i)
        if cnt == V:
            return distance
    return 0

def solution():
    N = int(input())
    M = int(input())

    graph = [[] for _ in range(N + 1)]
    for _ in range(M):
        A, B, C = map(int, sys.stdin.readline().split())
        graph[A].append((C, B))
        graph[B].append((C, A))
    print(PRIM(graph, N, 1))
solution()

https://www.acmicpc.net/problem/1922

Categories:

Updated:

Leave a comment