[백준] 1916번 최소비용 구하기

거북이·2023년 8월 25일
0

백준[골드5]

목록 보기
69/82
post-thumbnail

💡문제접근

  • 개선된 다익스트라 알고리즘 (시간 복잡도 : O(E log V))

💡코드(메모리 : 58532KB, 시간 : 352ms)

import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)

N = int(input())
M = int(input())
graph = [[] for _ in range(N+1)]
distance = [INF] * (N+1)
for _ in range(M):
    a, b, c = map(int, input().strip().split())
    graph[a].append([b, c])
start, end = map(int, input().strip().split())

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]))
    return distance

# A번 도시에서 출발(다익스트라 알고리즘)
result = dijkstra(start)
# B번 도시에 도착
print(result[end])

💡소요시간 : 17m

0개의 댓글