forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2.py
More file actions
50 lines (45 loc) ยท 1.81 KB
/
2.py
File metadata and controls
50 lines (45 loc) ยท 1.81 KB
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
40
41
42
43
44
45
46
47
48
49
50
import heapq
import sys
input = sys.stdin.readline
INF = int(1e9) # ๋ฌดํ์ ์๋ฏธํ๋ ๊ฐ์ผ๋ก 10์ต์ ์ค์
# ๋
ธ๋์ ๊ฐ์, ๊ฐ์ ์ ๊ฐ์๋ฅผ ์
๋ ฅ๋ฐ๊ธฐ
n, m = map(int, input().split())
# ์์ ๋
ธ๋ ๋ฒํธ๋ฅผ ์
๋ ฅ๋ฐ๊ธฐ
start = int(input())
# ๊ฐ ๋
ธ๋์ ์ฐ๊ฒฐ๋์ด ์๋ ๋
ธ๋์ ๋ํ ์ ๋ณด๋ฅผ ๋ด๋ ๋ฆฌ์คํธ๋ฅผ ๋ง๋ค๊ธฐ
graph = [[] for i in range(n + 1)]
# ์ต๋จ ๊ฑฐ๋ฆฌ ํ
์ด๋ธ์ ๋ชจ๋ ๋ฌดํ์ผ๋ก ์ด๊ธฐํ
distance = [INF] * (n + 1)
# ๋ชจ๋ ๊ฐ์ ์ ๋ณด๋ฅผ ์
๋ ฅ๋ฐ๊ธฐ
for _ in range(m):
a, b, c = map(int, input().split())
# a๋ฒ ๋
ธ๋์์ b๋ฒ ๋
ธ๋๋ก ๊ฐ๋ ๋น์ฉ์ด c๋ผ๋ ์๋ฏธ
graph[a].append((b, c))
def dijkstra(start):
q = []
# ์์ ๋
ธ๋๋ก ๊ฐ๊ธฐ ์ํ ์ต๋จ ๊ฒฝ๋ก๋ 0์ผ๋ก ์ค์ ํ์ฌ, ํ์ ์ฝ์
heapq.heappush(q, (0, start))
distance[start] = 0
while q: # ํ๊ฐ ๋น์ด์์ง ์๋ค๋ฉด
# ๊ฐ์ฅ ์ต๋จ ๊ฑฐ๋ฆฌ๊ฐ ์งง์ ๋
ธ๋์ ๋ํ ์ ๋ณด ๊บผ๋ด๊ธฐ
dist, now = heapq.heappop(q)
# ํ์ฌ ๋
ธ๋๊ฐ ์ด๋ฏธ ์ฒ๋ฆฌ๋ ์ ์ด ์๋ ๋
ธ๋๋ผ๋ฉด ๋ฌด์
if distance[now] < dist:
continue
# ํ์ฌ ๋
ธ๋์ ์ฐ๊ฒฐ๋ ๋ค๋ฅธ ์ธ์ ํ ๋
ธ๋๋ค์ ํ์ธ
for i in graph[now]:
cost = dist + i[1]
# ํ์ฌ ๋
ธ๋๋ฅผ ๊ฑฐ์ณ์, ๋ค๋ฅธ ๋
ธ๋๋ก ์ด๋ํ๋ ๊ฑฐ๋ฆฌ๊ฐ ๋ ์งง์ ๊ฒฝ์ฐ
if cost < distance[i[0]]:
distance[i[0]] = cost
heapq.heappush(q, (cost, i[0]))
# ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ ์ํ
dijkstra(start)
# ๋ชจ๋ ๋
ธ๋๋ก ๊ฐ๊ธฐ ์ํ ์ต๋จ ๊ฑฐ๋ฆฌ๋ฅผ ์ถ๋ ฅ
for i in range(1, n + 1):
# ๋๋ฌํ ์ ์๋ ๊ฒฝ์ฐ, ๋ฌดํ(INFINITY)์ด๋ผ๊ณ ์ถ๋ ฅ
if distance[i] == INF:
print("INFINITY")
# ๋๋ฌํ ์ ์๋ ๊ฒฝ์ฐ ๊ฑฐ๋ฆฌ๋ฅผ ์ถ๋ ฅ
else:
print(distance[i])