1753-백준

Halo·2021년 11월 18일
0

Algorithm

목록 보기
2/5

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

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])
profile
일단 해보자 !

0개의 댓글