코딩테스트 대비/단계별 코딩 테스트 준비(27일 과정)

[다익스트라/Python] 1753번: 최단경로 - 효과는 굉장했다!

bluetag_boy 2022. 2. 19. 16:57
반응형
 

1753번: 최단경로

첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V)가

www.acmicpc.net

 

알고리즘 분류

  • 그래프 이론
  • 다익스트라

 

 

SOLUTION

import sys
import heapq
INF = sys.maxsize

def dijkstra(start): 
    heap = []
    distance[start] = 0
    # heap에 (가중치, 노드) 순으로 넣어놔야 시간을 더 줄일 수 있다
    heapq.heappush(heap, (0, start))

    while heap:
        cost, now = heapq.heappop(heap)
      
        if distance[now] < cost: 
            continue

        for next_node, weight in graph[now]:
            next_cost = cost + weight 
            # 더 적은 비용으로 해당 노드를 갈 수 있을 때 갱신해줌
            if next_cost < distance[next_node]:
                distance[next_node] = next_cost
                heapq.heappush(heap, (next_cost, next_node))


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

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

dijkstra(K)

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