
풀이.
다익스트라 알고리즘을 이용해서 출발점에서 도착점까지의 최단 경로 + 도착점에서 출발점까지의 최단 경로를
구해서 최댓값을 출력해주면 된다.
소스코드.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 다익스트라 | |
import sys | |
import heapq | |
def dijkstra(start): | |
heap = [] | |
dp = [inf] * (n + 1) | |
dp[start] = 0 | |
heapq.heappush(heap, (0, start)) | |
while heap: | |
now_weight, now = heapq.heappop(heap) | |
if dp[now] < now_weight: | |
continue | |
for next, cost in graph[now]: | |
next_weight = now_weight + cost | |
if next_weight < dp[next]: | |
dp[next] = next_weight | |
heapq.heappush(heap, (next_weight, next)) | |
return dp | |
input = sys.stdin.readline | |
inf = float('inf') | |
n, m, x = map(int, input().split()) | |
graph = [[] for _ in range(n+1)] | |
for _ in range(m): | |
u, v, w = map(int, input().split()) | |
graph[u].append((v,w)) | |
answer = 0 | |
for i in range(1, n+1): | |
answer = max(answer, dijkstra(i)[x] + dijkstra(x)[i]) | |
print(answer) |
'프로그래밍 > 백준' 카테고리의 다른 글
[백준] 18352. 특정 거리의 도시 찾기 - 파이썬 (0) | 2021.09.27 |
---|---|
[백준] 16975. 수열과 쿼리 21 - 파이썬 (0) | 2021.09.25 |
[백준] 1517 버블 소트 - 파이썬 (0) | 2021.09.23 |
[백준] 1766 문제집 - 파이썬 (0) | 2021.09.20 |
[백준] 3665. 최종 순위 - 파이썬 (0) | 2021.09.15 |