본문 바로가기
알고리즘

Dijkstra

by 이재현9999 2024. 10. 11.
import sys
input = sys.stdin.readline
import heapq

n = int(input())
m = int(input())

INF = 1e8

graph = [[] for _ in range(n+1)]
distance = [INF] * (n+1)

for _ in range(m):
    u, v, w = map(int, input().split())
    graph[u].append((v, w))

start, end = map(int, input().split())

def dijkstra(start):
    q = []
    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]:
            if dist+i[1] < distance[i[0]]:
                distance[i[0]] = dist + i[1]
                heapq.heappush(q, (dist+i[1], i[0]))

dijkstra(start)
print(distance[end])

'알고리즘' 카테고리의 다른 글

Segment Tree  (0) 2024.10.11
Floyd-Warshall  (0) 2024.10.11
Bellman-Ford  (0) 2024.10.11
[python] 백준 2667번 - 단지번호붙이기  (0) 2024.08.15
[python] 백준 2630번 - 색종이 만들기  (0) 2024.08.11