Notice
Recent Posts
Recent Comments
Link
나의 개발일지
[백준] 1916 최소비용 구하기 [Python, 파이썬] 본문
- 문제 : https://www.acmicpc.net/problem/1916
- 🔑 Dijkstra 알고리즘
import sys
from collections import defaultdict
from heapq import heappush, heappop
input = sys.stdin.readline
n = int(input()) # 도시 개수
m = int(input()) # 버스 개수
graph = defaultdict(list)
for i in range(m):
s, e, c = map(int, input().split())
graph[s].append((c, e)) # 출발지 : [(비용, 도착지)]
start, end = map(int, input().split())
INF = int(1e9)
cost = [INF] * (n+1)
cost[start] = 0
q = []
heappush(q, (0, start))
while q:
now_cost, now = heappop(q)
if now_cost > cost[now]: # 같은 경로로 갈 때 비용이 더 들면 넘기기
continue
for next_cost, next in graph[now]:
newCost = now_cost + next_cost
if cost[next] > newCost:
cost[next] = newCost
q.append((newCost, next))
print(cost[end])
'백준' 카테고리의 다른 글
[백준] 2667 단지 번호 붙이기 [Python, 파이썬] (0) | 2023.10.15 |
---|---|
[백준] 11404 플로이드 [Python, 파이썬] (0) | 2023.10.15 |
[백준] 18352 특정 거리의 도시 찾기 [Python, 파이썬] (1) | 2023.10.13 |
[백준] 11057 오르막수 [Python, 파이썬] (0) | 2023.10.12 |
[백준] 12919 A와 B 2 [Python, 파이썬] (0) | 2023.10.03 |
Comments