백준 1753번 - 최단경로

윤여준·2022년 5월 23일
0

백준 풀이

목록 보기
15/35
post-thumbnail

문제

문제 링크 : https://www.acmicpc.net/problem/1753

풀이

(풀이 방법은 나동빈님의 '이것이 코딩테스트다' 책을 참고했다.)

전형적인 다익스트라 문제이다.

간단하게 다익스트라를 구현하는 방법도 있지만 시간 단축을 위해서 힙을 통해 다익스트라를 구현했다.

다익스트라 알고리즘은 다음과 같다.

  1. 출발 노드를 설정한다.
  2. 최단 거리 테이블을 초기화한다.
  3. 방문하지 않은 노드 중에서 최단 거리가 가장 짧은 노드를 선택한다.
  4. 해당 노드를 거쳐 다른 노드로 가는 비용을 계산하여 최단 거리 테이블을 갱신한다.
  5. 위 과정에서 3과 4번을 반복한다.
import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)

n, m = map(int,input().split())

start = int(input())

graph = [[] for i in range(n + 1)]

distance = [INF] * (n + 1)

for _ in range(m):
    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:
        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]))

dijkstra(start)

for i in range(1, n + 1):
    if distance[i] == INF:
        print("INF")
    else:
        print(distance[i])
profile
Junior Backend Engineer

0개의 댓글