동캄의 코딩도장

백준 1753 [최단경로] 파이썬 본문

코테/BOJ

백준 1753 [최단경로] 파이썬

동 캄 2022. 5. 17. 00:10

https://www.acmicpc.net/problem/1753

 

1753번: 최단경로

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

www.acmicpc.net

# 백준 1753 최단경로
import sys
import heapq
from collections import defaultdict
input = sys.stdin.readline

V, E = map(int, input().split())
K = int(input())
graph = defaultdict(list)
for _ in range(E):
    a, b, cost = map(int, input().split())
    graph[a].append([b, cost])


def dijkstra(graph, start):
    distances = {node: float('INF') for node in range(1, V+1)}
    distances[start] = 0
    queue = []
    heapq.heappush(queue, [distances[start], start])
    while queue:
        current_distance, current_destination = heapq.heappop(queue)

        if distances[current_destination] < current_distance:
            continue

        for new_destination, new_distance in graph[current_destination]:
            distance = current_distance+new_distance
            if distance < distances[new_destination]:
                distances[new_destination] = distance
                heapq.heappush(queue, [distance, new_destination])
    return distances


distances = dijkstra(graph, K)
for val in distances.values():
    if val == float('inf'):
        print('INF')
    else:
        print(val)

다익스트라를 이용한 문제이다. 다른분의 풀이를 참고하여 문제를 해결하였다..

(좀 더 많은 유형의 문제를 풀어보자!)

'코테 > BOJ' 카테고리의 다른 글

백준 17396 [백도어] 파이썬  (0) 2022.05.17
백준 5972 [택배 배송] 파이썬  (0) 2022.05.17
백준 9019 [DSLR] 파이썬  (0) 2022.04.18
백준 16236 [아기 상어] 파이썬  (0) 2022.04.17
백준 1377 [버블 소트] 파이썬  (0) 2022.04.16