[Python] [BOJ] 최소비용 구하기(1916)

긍정왕·2021년 8월 2일
1

Algorithm

목록 보기
62/69

💡 문제 해결

📌 목적지에 도착하면 종료하게 두어도 통과가 되는것 같다.



🧾 문제 설명

N개의 도시가 있다. 그리고 한 도시에서 출발하여 다른 도시에 도착하는 M개의 버스가 있다. 
우리는 A번째 도시에서 B번째 도시까지 가는데 드는 버스 비용을 최소화 시키려고 한다. 
A번째 도시에서 B번째 도시까지 가는데 드는 최소비용을 출력하여라. 
도시의 번호는 1부터 N까지이다.

문제보기



🖨 입출력



📝 풀이

import sys, heapq
from collections import defaultdict


input = sys.stdin.readline

N = int(input())
M = int(input())
nodes = defaultdict(list)
for _ in range(M):
    s, e, c = map(int, input().split())
    nodes[s].append((e, c))
start, end = map(int, input().split())

distance = {i: float('inf') if i != start else 0 for i in range(1, N + 1)}
heap = []
heapq.heappush(heap, (0, start))
while heap:
    current_dis, current_node = heapq.heappop(heap)
    if distance[current_node] < current_dis: continue
    # if current_node == end:
    #     print(current_dis)
    #     exit()
    for next_node, dis in nodes[current_node]:
        if distance[next_node] > distance[current_node] + dis:
            distance[next_node] = distance[current_node] + dis
            heapq.heappush(heap, (distance[next_node], next_node))

answer = distance[end]

print(answer)

profile
Impossible + 땀 한방울 == I'm possible

0개의 댓글