Coding Test
[백준] 최소비용 구하기
상상쓰
2021. 11. 9. 14:35
https://www.acmicpc.net/problem/1916
1916번: 최소비용 구하기
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그
www.acmicpc.net
출발 도시와 도착 도시가 같은 버스가 있을 수 있다는 생각을 처음에 못 했다. 그래서 코드를 추가했고 비용이 0인 버스가 있어서 fee = {} 비어있을 때랑 값이 있을 때 나눠서 다익스트라 알고리즘으로 풀었다.
import sys
from collections import defaultdict, deque
N = int(sys.stdin.readline())
M = int(sys.stdin.readline())
bus = [list(map(int, sys.stdin.readline().split())) for i in range(M)]
start, end = map(int, sys.stdin.readline().split())
dic = defaultdict(list)
fee = {}
queue = deque()
for x, y, d in bus:
dic[x].append((y, d))
fee[start] = 0
for y, d in dic[start]:
if y not in fee:
fee[y] = d
if y != end:
queue.append(y)
else:
if fee[y] > d:
fee[y] = d
while queue:
x = queue.popleft()
for y, d in dic[x]:
if y not in fee:
fee[y] = fee[x] + d
if y != end:
queue.append(y)
else:
if fee[y] > fee[x] + d:
fee[y] = fee[x] + d
if y != end:
queue.append(y)
print(fee[end])