백준 1916(파이썬) - 최소비용구하기
resilient
·2021. 4. 1. 13:29
728x90
반응형
1916번: 최소비용 구하기
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그
www.acmicpc.net
import sys
from heapq import heappop,heappush
input = sys.stdin.readline
inf = 987654321
n = int(input())
m = int(input())
graph = [[] for _ in range(n+1)]
dp = [inf for _ in range(n+1)]
for i in range(m):
a,b,cost = map(int,input().split())
graph[a].append([b,cost])
start,end = map(int,input().split())
def dijkstra(start):
dp[start] = 0
heap=[]
heappush(heap,[0,start])
while heap:
cost, node = heappop(heap)
if dp[node] < cost:
continue
for n_node, weight in graph[node]:
dp_cost = cost + weight
if dp[n_node] > dp_cost:
dp[n_node] = dp_cost
heappush(heap, [dp_cost, n_node])
dijkstra(start)
print(dp[end])
반응형
'자료구조 & 알고리즘 > 백준(Baekjoon)' 카테고리의 다른 글
백준 1939(파이썬) - 중량제한 (0) | 2021.04.05 |
---|---|
백준 2146(파이썬) - 다리만들기 (0) | 2021.04.05 |
백준 2512(파이썬) - 예산 (0) | 2021.03.25 |
백준 10815(파이썬) - 숫자카드 (0) | 2021.03.20 |
백준 14889(파이썬) - 스타트와 링크 (0) | 2021.03.02 |