BOJ - 1504 - 특정한 최단 경로

Updated:

import sys
from heapq import heappush, heappop

def Dijkstra(K, graph, V):
    heap = []
    distance = [1e9] * (V + 1)
    distance[K] = 0
    heappush(heap, (0, K))

    while heap:
        weight, location = heappop(heap)

        if distance[location] < weight:
            continue

        for l, w in graph[location]:
            w += weight
            if w < distance[l]:
                distance[l] = w
                heappush(heap, (w, l))

    return distance

def solution():
    V, E = map(int, sys.stdin.readline().split())
    graph = [[] for _ in range(V + 1)]

    for _ in range(E):
        u, v, w = map(int, sys.stdin.readline().split())
        graph[u].append([v, w])
        graph[v].append([u, w])

    v1, v2 = map(int, sys.stdin.readline().split())

    vertex0 = Dijkstra(1, graph, V)
    vertex1 = Dijkstra(v1, graph, V)
    vertex2 = Dijkstra(v2, graph, V)

    result = min(vertex0[v1] + vertex1[v2] + vertex2[V], vertex0[v2] + vertex2[v1] + vertex1[V])
    print(result if result < 1e9 else -1)

solution()

https://www.acmicpc.net/problem/1504

Categories:

Updated:

Leave a comment