https://www.acmicpc.net/problem/1238
import sys
import heapq
input = sys.stdin.readline
n, m, x = map(int, input().split()) # n : 학생 수, m : 도로 개수 x : 도착해야하는곳
graph = [[]for _ in range(n+1)]
res = [0] * (n+1)
for _ in range(m):
u, v, t = map(int, input().split())
graph[u].append((v, t))
def dijkstraStart(start, x):
temp = graph
weight = [int(1e9)] * (n+1)
heap = []
weight[start] = 0
heapq.heappush(heap, (0, start))
while heap:
dist, node = heapq.heappop(heap)
if dist > weight[node]:
continue
for next in temp[node]:
cost = dist + next[1]
if cost < weight[next[0]]:
weight[next[0]] = cost
heapq.heappush(heap, (cost, next[0]))
return weight[x]
def dijkstraEnd(start, x):
temp = graph
weight = [int(1e9)] * (n+1)
heap = []
weight[start] = 0
heapq.heappush(heap, (0, start))
while heap:
dist, node = heapq.heappop(heap)
if dist > weight[node]:
continue
for next in temp[node]:
cost = dist + next[1]
if cost < weight[next[0]]:
weight[next[0]] = cost
heapq.heappush(heap, (cost, next[0]))
return weight[i]
for i in range(1, n+1):
a = dijkstraStart(i, x) + dijkstraEnd(x, i)
res[i] = a
print(max(res))
다익스트라 알고리즘을 이용해 풀었다.
함수를 총 2개로 나누어 풀었다.
두 함수에서 return한 값을 합쳐 배열에 저장 후, 최대값을 출력한다.