import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)
v, e = map(int, input().split())
graph = [[] for _ in range(v + 1)]
for _ in range(e):
x, y, cost = map(int, input().split())
graph[x].append((y, cost))
graph[y].append((x, cost))
def dijkstra(start):
distance = [INF] * (v + 1)
q = []
heapq.heappush(q, (0, start))
distance[start] = 0
while q:
dist, now = heapq.heappop(q)
if distance[now] < dist:
continue
for i in graph[now]:
cost = dist + i[1]
if distance[i[0]] > cost:
distance[i[0]] = cost
heapq.heappush(q, (cost, i[0]))
return distance
v1, v2 = map(int, input().split())
original_distance = dijkstra(1)
v1_distance = dijkstra(v1)
v2_distance = dijkstra(v2)
v1_path = original_distance[v1] + v1_distance[v2] + v2_distance[v]
v2_path = original_distance[v2] + v2_distance[v1] + v1_distance[v]
result = min(v1_path, v2_path)
print(result if result < INF else -1)
'문제풀이 > 백준(Boj) 문제풀이' 카테고리의 다른 글
[백준][DFS/DP] 1707. 이분 그래프 (파이썬/Python) (0) | 2022.01.20 |
---|---|
[백준][BFS] 7562.나이트의 이동 (파이썬/Python) (0) | 2022.01.17 |
[백준][자료구조/힙] 1715.카드 정렬하기 (파이썬/Python) (0) | 2022.01.11 |
[백준][DFS] 1967. 트리의 지름 (파이썬/Python) (0) | 2022.01.10 |
[백준][자료구조/힙] 1655.가운데를 말해요 (파이썬/Python) (0) | 2022.01.10 |