1753-백준

945 단어 pythonpython

백준
다익스트라
시작점으로 부터 나머지 정점간의 최단거리

import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)

V, E = map(int, input().split())
K = int(input())
graph = [[] for _ in range(V+1)]
distance = [INF]*(V+1)

for _ in range(E):
    a, b, c = map(int, input().split())
    graph[a].append((b,c))

def dijkstra(start):
    q = []
    heapq.heappush(q, (0, start))
    distance[start] = 0
    while q:
        w, vertex = heapq.heappop(q)
        if distance[vertex] < w:
            continue
        for i in graph[vertex]:
            cost = w + i[1]
            if cost < distance[i[0]]:
                distance[i[0]] = cost
                heapq.heappush(q, (cost, i[0]))

dijkstra(K)

for i in range(1, V+1):
    if distance[i] == INF:
        print("INF")
    else:
        print(distance[i])

좋은 웹페이지 즐겨찾기