<문제 링크>
https://www.acmicpc.net/problem/1753
<정답 코드>
sol1 ) 다익스트라 알고리즘으로 최단경로 탐색
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import sys
import heapq
input = sys.stdin.readline
def dijkstra(s, dis):
dis[s] = 0
q = []
heapq.heappush(q, (0, s))
while q:
cur_dis, now = heapq.heappop(q)
if cur_dis > dis[now]:
continue
for n, weight in graph[now]:
cost = cur_dis + weight
if cost < dis[n]:
dis[n] = cost
heapq.heappush(q, (cost, n))
V, E = map(int, input().split())
K = int(input())
graph = [[] for _ in range(V+1)]
for _ in range(E):
u, v, w = map(int, input().split())
graph[u].append((v, w))
# 최단경로 탐색 전 무한대(inf)로 초기화
dis = [float('inf')] * (V+1)
dijkstra(K, dis)
for i in dis[1:]:
if i != float('inf'):
print(i)
# i가 무한대인 경우 경로 존재 x
else:
print('INF')
|
cs |
최단경로 문제의 다양한 상황과 조건에 따라 경로 탐색하는 방법을 더 연습해야겠다
'프로그래밍 > Python' 카테고리의 다른 글
백준_python 1158번 요세푸스 문제 (deque, 수학, 시간복잡도) (1) | 2024.09.15 |
---|---|
백준_python 5397번 키로거 (스택, 연결리스트(LinkedList)) (0) | 2024.09.14 |
백준_python 13549번 숨바꼭질 (메모리 초과, BFS, 최단거리) (0) | 2024.09.09 |
백준_python 3273번 두 수의 합 (정렬, 투 포인터) (6) | 2024.09.02 |
백준_python 1068번 트리 (DFS) (0) | 2024.08.23 |