본문 바로가기

알고리즘 문제풀이

도시 건설(백준 21924)

import sys
import heapq 
input= sys.stdin.readline
n,m= map(int, input().split())
gra=[[]for _ in range(n+1)]
visit= [0 for _ in range(n+1)]
total = 0 
ans =0 

for i in range(m):
    a,b,c = map(int, input().split())
    total += c 
    gra[a].append((b,c))
    gra[b].append((a,c))

def prim(start):
    global ans 
    q = [[0,start]]
    heapq.heapify(q)
    while q :
        cost, now =heapq.heappop(q)
        if visit[now] ==0:
            visit[now] = 1 
            ans+= cost 
            for nextnode, nextcost in gra[now]:
                if visit[nextnode] ==0 :
                    heapq.heappush(q,(nextcost,nextnode))
                    
prim(1)

print(total-ans if (0 not in visit[1:]) else -1)

'알고리즘 문제풀이' 카테고리의 다른 글

우주신과의 교감(백준 1774)  (0) 2023.08.04
Beads (백준 11143)  (0) 2023.08.02
나만 안되는 연애(백준 14621)  (0) 2023.07.31
행성 연결 (백준 16398)  (0) 2023.07.29
발전소 설치(백준 1277)  (0) 2023.07.29