출처 : https://www.acmicpc.net/problem/5972
코드
import heapq
def dijkstra(graph, start):
INF = float('inf')
N = len(graph)
distance = [INF] * N
distance[start] = 0
pq = []
heapq.heappush(pq, (start, 0))
while pq:
now, dist = heapq.heappop(pq)
for neighbor, weight in graph[now]:
cost = dist + weight
if cost < distance[neighbor]:
distance[neighbor] = cost
heapq.heappush(pq, (neighbor, cost))
return distance
N, M = map(int, input().split())
graph = { i : [] for i in range(N + 1)}
for _ in range(M):
start, end, distance = map(int, input().split())
graph[start].append((end, distance))
graph[end].append((start, distance))
shortest_distances = dijkstra(graph, 1)
print(shortest_distances[N])
풀이
최소 비용을 구하는 문제이기에 다익스트라를 사용했습니다.
파이썬에서는 heapq로 다익스트라를 구현하기에 해봤습니다.
각 정점에 도달하는 최단거리를 갱신합니다.
→ 현재 노드까지 비용 + 다음 노드 까지의 비용이 현재 기록된 비용보다 적으면 갱신해줍니다.
그리고 이를 heap에 저장해줍니다.
728x90
'백준 > 골드' 카테고리의 다른 글
음악프로그램(2623) - Python, 위상정렬 (0) | 2025.01.24 |
---|---|
숫자고르기 - Python (0) | 2025.01.22 |
피자판매 2632번 - Pyton, 부분합 (0) | 2025.01.01 |
백준 > 2931번 > 가스관 - JAVA (0) | 2023.08.29 |
백준 > 17471번 > 게리멘더링 - JAVA (1) | 2023.04.12 |