문제 소개

5 6 # 정점의 개수 V 간선의 개수 E
1 # 시작 정점 번호 K
5 1 1 # (u, v, w) u에서 v로 가는 가중치 w인 간선
1 2 2
1 3 3
2 3 4
2 4 5
3 4 6
0
2
3
7
INF

문제에 사용한 알고리즘

문제 아이디어

문제에 사용한 자료구조

코드

import heapq

INF = int(1e9)
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]:
            cost =dist+ i[1]
            if cost < distance[i[0]] :
                distance[i[0]] = cost
                heapq.heappush(q,(cost,i[0]))

V, E = map(int,input().split())
K = int(input()) 

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

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

dijkstra(K)

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