출처 : https://www.acmicpc.net/problem/1916
1916번: 최소비용 구하기
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그
www.acmicpc.net
다익스트라 알고리즘을 사용하는 기본적인 문제이다.
import heapq
import sys
input = sys.stdin.readline
n = int(input())
m = int(input())
adj = [[] for _ in range(n + 1)]
for _ in range(m):
x, y, c = map(int, input().split())
adj[x].append([c, y])
start, end = map(int, input().split())
def dijkstra(adj, n, start, end):
heap = []
heapq.heappush(heap, [0, start])
INF = float('inf')
dist = [INF] * (n + 1)
dist[start] = 0
while heap:
cost, node = heapq.heappop(heap)
if cost > dist[node]:
continue
for C, N in adj[node]:
C += cost
if C < dist[N]:
dist[N] = C
heapq.heappush(heap, [C, N])
return dist[end]
print(dijkstra(adj, n, start, end))
'Coding Test > Baekjoon' 카테고리의 다른 글
[DK]백준 - 열 개씩 끊어 출력하기(11721) - C++ (0) | 2021.07.14 |
---|---|
[DK]백준 - 숫자의 개수(2577) - C++ (0) | 2021.07.12 |
[ST]백준 - 정열적인 정렬(16212) - Java (0) | 2021.07.07 |
[ST]백준 - 스택(10828) - Java (0) | 2021.07.05 |
[DK]백준 - 최단경로(1753) - Python (0) | 2021.07.01 |