forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path4.py
More file actions
49 lines (44 loc) ยท 1.81 KB
/
4.py
File metadata and controls
49 lines (44 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
import sys
input = sys.stdin.readline
INF = int(1e9) # ๋ฌดํ์ ์๋ฏธํ๋ ๊ฐ์ผ๋ก 10์ต์ ์ค์
# ๋
ธ๋์ ๊ฐ์, ๊ฐ์ ์ ๊ฐ์๋ฅผ ์
๋ ฅ๋ฐ๊ธฐ
n, m = map(int, input().split())
# ๋ชจ๋ ๊ฐ์ ์ ๋ํ ์ ๋ณด๋ฅผ ๋ด๋ ๋ฆฌ์คํธ ๋ง๋ค๊ธฐ
edges = []
# ์ต๋จ ๊ฑฐ๋ฆฌ ํ
์ด๋ธ์ ๋ชจ๋ ๋ฌดํ์ผ๋ก ์ด๊ธฐํ
distance = [INF] * (n + 1)
# ๋ชจ๋ ๊ฐ์ ์ ๋ณด๋ฅผ ์
๋ ฅ๋ฐ๊ธฐ
for _ in range(m):
a, b, c = map(int, input().split())
# a๋ฒ ๋
ธ๋์์ b๋ฒ ๋
ธ๋๋ก ๊ฐ๋ ๋น์ฉ์ด c๋ผ๋ ์๋ฏธ
edges.append((a, b, c))
def bf(start):
# ์์ ๋
ธ๋์ ๋ํด์ ์ด๊ธฐํ
distance[start] = 0
# ์ ์ฒด n - 1๋ฒ์ ๋ผ์ด๋(round)๋ฅผ ๋ฐ๋ณต
for i in range(n):
# ๋งค ๋ฐ๋ณต๋ง๋ค "๋ชจ๋ ๊ฐ์ "์ ํ์ธํ๋ฉฐ
for j in range(m):
cur_node = edges[j][0]
next_node = edges[j][1]
edge_cost = edges[j][2]
# ํ์ฌ ๊ฐ์ ์ ๊ฑฐ์ณ์ ๋ค๋ฅธ ๋
ธ๋๋ก ์ด๋ํ๋ ๊ฑฐ๋ฆฌ๊ฐ ๋ ์งง์ ๊ฒฝ์ฐ
if distance[cur_node] != INF and distance[next_node] > distance[cur_node] + edge_cost:
distance[next_node] = distance[cur_node] + edge_cost
# n๋ฒ์งธ ๋ผ์ด๋์์๋ ๊ฐ์ด ๊ฐฑ์ ๋๋ค๋ฉด ์์ ์ํ์ด ์กด์ฌ
if i == n - 1:
return True
return False
# ๋ฒจ๋ง ํฌ๋ ์๊ณ ๋ฆฌ์ฆ์ ์ํ
negative_cycle = bf(1) # 1๋ฒ ๋
ธ๋๊ฐ ์์ ๋
ธ๋
if negative_cycle:
print("-1")
else:
# 1๋ฒ ๋
ธ๋๋ฅผ ์ ์ธํ ๋ค๋ฅธ ๋ชจ๋ ๋
ธ๋๋ก ๊ฐ๊ธฐ ์ํ ์ต๋จ ๊ฑฐ๋ฆฌ๋ฅผ ์ถ๋ ฅ
for i in range(2, n + 1):
# ๋๋ฌํ ์ ์๋ ๊ฒฝ์ฐ, -1์ ์ถ๋ ฅ
if distance[i] == INF:
print("-1")
# ๋๋ฌํ ์ ์๋ ๊ฒฝ์ฐ ๊ฑฐ๋ฆฌ๋ฅผ ์ถ๋ ฅ
else:
print(distance[i])