티스토리 뷰

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

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 heapq
import sys
 
input = sys.stdin.readline
 
INF = int(1e9)
v, e = map(int, input().split())
start = int(input())
dist = [INF] * (v + 1)
 
route = dict()
for _ in range(e):
    u, d, w = map(int, input().split())
    if u not in route:
        route[u] = list()
    route[u].append((w, d))
 
 
dist[start] = 0
= list()
heapq.heappush(q, (0, start))
 
while q:
    cost, now = heapq.heappop(q)
    if cost > dist[now]:
        continue
    if now not in route:
        continue
    for c, node in route[now]:
        if dist[node] > cost + c:
            dist[node] = cost + c
            heapq.heappush(q, (dist[node], node))
 
for i in range(1, v + 1):
    if dist[i] < INF:
        print(dist[i])
    else:
        print('INF')
 
cs

다익스트라 알고리즘을 이용해서 풀면 된다.

파이썬3을 이용할 경우, sys.stdin.readline 안쓰면 시간 펑난다.

PyPy3로 돌리면 그냥 input() 써도 안터지더라

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함