๐ algorithm/boj
BOJ 5972 - ํ๋ฐฐ ๋ฐฐ์ก
HandHand
2021. 6. 10. 22:55
๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 5972๋ฒ
ํ์ด ๊ณผ์
ํน์ ์์ ์ง์ ์์ ๋ชฉํ ์ง์ ์ ๋๋ฌํ๊ธฐ ์ํ ์ต์ ๋น์ฉ์ ์ฐพ๋ ๋ฌธ์ ์
๋๋ค.๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ
์ ์ด์ฉํด์ ํ ์ ์ ์์ ๋ชจ๋ ์ ์ ๊น์ง์ ์ต๋จ ๋น์ฉ์ ๊ตฌํ๋ฉด ElogV
์ ์๊ฐ ๋ณต์ก๋๋ก ๊ตฌํ ์ ์์ต๋๋ค.
์ฝ๋
import sys
import heapq
INF = 2e9
def dijkstra(frm, to):
dist = [INF] * (N + 1)
pq = []
dist[frm] = 0
heapq.heappush(pq, [0, frm])
while pq:
cost, here = heapq.heappop(pq)
if dist[here] < cost:
continue
for there, there_cost in graph[here]:
next_cost = cost + there_cost
if dist[there] > next_cost:
dist[there] = next_cost
heapq.heappush(pq, [next_cost, there])
return dist[to]
def make_graph():
graph = [[] for _ in range(N + 1)]
for frm, to, cost in edges:
graph[frm].append([to, cost])
graph[to].append([frm, cost])
return graph
def solution():
answer = dijkstra(1, N)
return answer
if __name__ == '__main__':
N, M = list(map(int, sys.stdin.readline().split()))
edges = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]
graph = make_graph()
answer = solution()
print(answer)
๋ฐ์ํ