๋
ธ๋๋ณ distance ๋ฆฌ์คํธ
๋
ธ๋ ๋ณ ์ฐ๊ฒฐ ๋
ธ๋ ์ ๋ณด
์ํํ๋์ง Visited ๋ฆฌ์คํธ์ ์์๊ฐ๋ฉฐ ์ํ
๊ฐ๋จํ ๊ตฌํ, ์๋ ๋๋ฆผ
import sys
INF = int(1e9)
# ๋
ธ๋์ ๊ฐ์, ๊ฐ์ ์ ๊ฐ
n, m = map(int,sys.stdin.readline().split())
# ์์ ๋
ธ๋ ๋ฒํธ ์
๋ ฅ
start = int(input())
# ๊ฐ ๋
ธ๋์ ์ฐ๊ฒฐ๋์ด ์๋ ๋
ธ๋์ ๋ํ ์ ๋ณด๋ฅผ ๋ด๋ ๋ฆฌ์คํธ
graph = [[] for i in range(n + 1)]
# ๋ฐฉ๋ฌธ ๋ฆฌ์คํธ
visited = [False] * (n + 1)
# ์ต๋จ ๊ฑฐ๋ฆฌ ํ
์ด๋ธ ๋ชจ๋ ๋ฌดํ์ผ๋ก ์ด๊ธฐํ
distance = [INF] * (n + 1)
# ๋ชจ๋ ๊ฐ์ ์ ๋ณด ์
๋ ฅ๋ฐ๊ธฐ
for _ in range(m):
# a ๋
ธ๋์์ b ๋
ธ๋๋ก ๊ฐ๋ ๋น์ฉ์ด c
a, b, c = map(int,input().split())
graph[a].append((b,c))
def get_smallest_node():
min_value = INF
index = 0
for i in range(1, n+1):
if distance[i] < min_value and not visited[i]:
min_value = distance[i]
index = i
return index
def dijkstra(start):
distance[start] = 0
visited[start] = True
for node_info in graph[start]:
distance[node_info[0]] = node_info[1]
for i in range(n-1):
now = get_smallest_node()
visited[now] = True
for node_info in graph[now]:
cost = distance[now] + node_info[1]
if cost < distance[node_info[0]]:
distance[node_info[0]] = cost
์ฐ์ ์์ํ(heapq) ๋ฅผ ์ด์ฉ
import heapq
import sys
# ๋
ธ๋์ ๊ฐ์, ๊ฐ์ ์ ๊ฐ์ ์
๋ ฅ๋ฐ๊ธฐ
n, m = map(int, input().split())
# ์์ ๋
ธ๋๋ฒํธ๋ฅผ ์
๋ ฅ๋ฐ๊ธฐ
start = int(input())
# ๊ฐ ๋
ธ๋์ ์ฐ๊ฒฐ๋์ด ์๋ ๋
ธ๋์ ๋ํ ์ ๋ณด๋ฅผ ๋ด๋ ๋ฆฌ์คํธ๋ฅผ ๋ง๋ค๊ธฐ
graph = [[] for i in range(n + 1)]
# ์ต๋จ ๊ฑฐ๋ฆฌ ํ
์ด๋ธ ์ด๊ธฐํ
INF = int(1e9)
distance = [INF] * (n + 1)
# ๊ฐ์ ์ ๋ณด ์
๋ ฅ๋ฐ๊ธฐ
for _ in range(m):
a, b, c = map(int, input().split())
graph[a].append((c, b))
def dijkstra(start):
q = []
# 1. ์์ ๋
ธ๋๋ก ๊ฐ๊ธฐ ์ํ ์ต๋จ ๊ฒฝ๋ก๋ 0 ์ผ๋ก ์ค์ ํ์ฌ, ํ์ ์ฝ์
heapq.heappush(q, (0, start))
distance[start] = 0
while q:
dist, now = heapq.heappop(q)
# 2. ํ์ฌ ๋
ธ๋๊ฐ ์ด๋ฏธ ์ฒ๋ฆฌ๋ ์ ์ด ์๊ณ ! ๊ฐ ์ค์ํจ, (๋ฐฉ๋ฌธ ์ ๋์ด ์์ผ๋ฉด INF ์ด๊ธฐ ๋๋ฌธ์, ๋ฌด์กฐ๊ฑด ํผ) ๊ทธ ๊ฐ์ด ๋ ์๋ค๋ฉด, ์ธ์ ๋
ธ๋๋ฅผ ํ์ํ์ง ์์
if distance[now] < dist:
continue
# ์ธ์ ๋
ธ๋ ํ์ธ
for dis, node in graph[now]:
cost = dist + dis
if cost < distance[node]:
distance[node] = cost
heapq.heappush(q, (cost, node))