728x90
https://school.programmers.co.kr/learn/courses/30/lessons/72413
import heapq
INF = int(1e9)
def dijkstra(n, start, graph): # end : a or b
distance = [INF]*(n+1)
distance[start] = 0
queue = []
heapq.heappush(queue, (0, start))
while queue:
dist, now = heapq.heappop(queue)
if dist < distance[now]:
continue
for next, next_dist in graph[now]:
if next_dist + dist < distance[next]:
distance[next] = next_dist + dist
heapq.heappush(queue, (next_dist + dist, next))
return distance
def solution(n, s, a, b, fares):
graph = [[] for _ in range(n+1)]
answer = INF
for x, y, cost in fares:
graph[x].append((y, cost))
graph[y].append((x, cost))
every_distance = [[]]
for i in range(1, n+1):
every_distance.append(dijkstra(n, i, graph))
# 현재 지점을 거치는 방법 vs 거치지 않는 방법을 비교
for i in range(1, n+1):
answer = min(answer, every_distance[s][i] + every_distance[i][a] + every_distance[i][b])
return answer
728x90
'Algorithm (PS)' 카테고리의 다른 글
[백준] 10159 저울 (Python/파이썬) - 플로이드워셜 (0) | 2023.02.20 |
---|---|
[백준] 2310번 : 어드벤처 게임 Python (0) | 2023.02.19 |
[백준] 22865 가장 먼 곳 Python (0) | 2023.02.15 |
[백준] 10830번: 행렬 제곱 - Python (0) | 2023.02.11 |
[백준] 9372번 상근이의 여행 Python (0) | 2023.02.09 |