https://www.acmicpc.net/problem/1753
1753번: 최단경로
첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V)가
www.acmicpc.net
import sys
import heapq
input = sys.stdin.readline
v, e = map(int, input().split())
start = int(input())
graph = [[] for _ in range(v + 1)]
for _ in range(e):
x, y, z = map(int, input().split())
graph[x].append((z, y))
cost = [float('inf')] * (v + 1)
cost[start] = 0
queue = []
heapq.heappush(queue, (0, start))
while queue:
weight, node = heapq.heappop(queue)
if cost[node] < weight:
continue
for w, n in graph[node]:
if weight + w < cost[n]:
cost[n] = weight + w
heapq.heappush(queue, (cost[n], n))
for i in cost[1:]:
print(i if i != float('inf') else "INF")
dijkstra 기본 문제인 최단 경로 문제이다.
heapq를 이용해 우선순위 큐처럼 사용했는데 한가지 간과한 점은
우선순위를 node 정보가 아닌 cost정보가 먼저 오도록 해야 한다는 것이다.
node 정보를 우선순위로 한다면 시간초과가 나니 주의!
'백준 알고리즘 (Baekjoon Algorithm)' 카테고리의 다른 글
[파이썬] 백준 알고리즘 No.24480 알고리즘 수업 - 깊이 우선 탐색 2 (0) | 2023.02.08 |
---|---|
[파이썬] 백준 알고리즘 No.24479 알고리즘 수업 - 깊이 우선 탐색 1 (0) | 2023.02.08 |
[파이썬] 백준 알고리즘 No.5525 IOIOI (0) | 2022.03.11 |
[파이썬] 백준 알고리즘 No.24498 blobnom - 블롭컵 대회 (0) | 2022.02.22 |
[파이썬] 백준 알고리즘 No.10815 숫자 카드 (0) | 2022.02.11 |