반응형
문제
https://www.acmicpc.net/problem/1647
풀이
import heapq
import sys
input = sys.stdin.readline
def prim(graph, start):
mst = []
visited = set()
min_heap = [(0, start, None)]
total_weight = 0
while min_heap:
weight, current, previous = heapq.heappop(min_heap)
if current in visited:
continue
visited.add(current)
total_weight += weight
if previous is not None:
mst.append((previous, current, weight))
for neighbor, edge_weight in graph[current]:
if neighbor not in visited:
heapq.heappush(min_heap, (edge_weight, neighbor, current))
return mst, total_weight
n, m = map(int, input().split())
graph = [[] for i in range(n + 1)]
for i in range(m):
a, b, c = map(int, input().split())
graph[a].append((b, c))
graph[b].append((a, c))
temp = a
mst, answer = prim(graph=graph, start=temp)
mst.sort(key=lambda a: -a[2])
long = mst[0][2]
# print(mst)
print(answer-long)
pypy로 제출해야 풀립니다.. 아마도
Prim알고리즘을 이용한 풀이입니다.
두 도시로 분할할 계획이기에 mst를 구한뒤 가장 큰 간선을 제거해주면 가장 작은 mst 2개가 완성됩니다.
반응형
'Programming > 알고리즘' 카테고리의 다른 글
[백준/Python] 1005번 ACM Craft (0) | 2025.03.18 |
---|---|
[백준/Python] 1644번 소수의 연속합 (0) | 2025.02.28 |
[백준/Python] 32986번 나는 건포도가 싫어요 (0) | 2025.01.18 |
[프로그래머즈/Python] 2022 블라인드 카카오 - 양궁대회 (0) | 2025.01.05 |
[백준/Python] 11758번 CCW (0) | 2025.01.02 |
댓글