백준 1916(최소비용 구하기) - python

2023. 10. 4. 21:15알고리즘(python)/최단경로

접근

특정한 노드에서 특정 노드까지 가는 최소 비용을 구하는 문제이다. 출발점에서 도착점까지 갈 수 있는 경우만 입력으로 오니 따로 예외처리를 신경쓰지 않고 다익스트라 알고리즘을 사용할 생각을 했다.

 

나의코드

import sys
from heapq import heappush, heappop
input = sys.stdin.readline


n = int(input())
m = int(input())
INT = int(10e9)
G = [[] for _ in range(n+1)]
for i in range(m):
    s, f, value = map(int,input().split())
    G[s].append((value,f))

def dik(start,finish):
    d = [INT] *(n+1)
    H  = []
    d[start] = 0
    H.append((0,start))
    while H:
        cost, node = heappop(H)
        if d[node] < cost:
            continue
        for cost2, node2 in G[node]:
            nextcost = cost+cost2
            if nextcost < d[node2]:
                d[node2] = nextcost
                heappush(H,(nextcost,node2))
    return d[finish]

s,f = map(int, input().split())
print(dik(s,f))