목차

특정한 최단 경로

ps
링크acmicpc.net/…
출처BOJ
문제 번호1504
문제명특정한 최단 경로
레벨골드 4
분류

다익스트라

시간복잡도O(ElogV)
인풋사이즈V<=800, E<=200,000
사용한 언어Python
제출기록58280KB / 388ms
최고기록344ms
해결날짜2022/09/16

풀이

코드

"""Solution code for "BOJ 1504. 특정한 최단 경로".

- Problem link: https://www.acmicpc.net/problem/1504
- Solution link: http://www.teferi.net/ps/problems/boj/1504

Tags: [Dijkstra]
"""

import sys
from teflib import graph as tgraph

INF = float('inf')


def main():
    N, E = [int(x) for x in sys.stdin.readline().split()]
    wgraph = [{} for _ in range(N)]
    for _ in range(E):
        a, b, c = [int(x) for x in sys.stdin.readline().split()]
        wgraph[a - 1][b - 1] = wgraph[b - 1][a - 1] = c
    v1, v2 = [int(x) for x in sys.stdin.readline().split()]

    dist_from_v1 = tgraph.dijkstra(wgraph, v1 - 1)
    dist_from_v2 = tgraph.dijkstra(wgraph, v2 - 1)
    dist = dist_from_v1[v2 - 1] + min(dist_from_v1[0] + dist_from_v2[N - 1],
                                      dist_from_v2[0] + dist_from_v1[N - 1])

    print('-1' if dist == INF else dist)


if __name__ == '__main__':
    main()