목차

국왕의 방문

ps
링크acmicpc.net/…
출처BOJ
문제 번호2982
문제명국왕의 방문
레벨골드 2
분류

다익스트라

시간복잡도O(ElogV)
인풋사이즈V<=1000, E<=10000
사용한 언어Python
제출기록32928KB / 92ms
최고기록84ms
해결날짜2022/03/16

풀이

코드

"""Solution code for "BOJ 2982. 국왕의 방문".

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

Tags: [Dijkstra]
"""

import heapq
import itertools
import sys

INF = float('inf')


def dijkstra(wgraph, blocked_period, source, dest):
    distances = [INF] * len(wgraph)
    distances[source] = 0
    heap = [(0, source)]
    while heap:
        dist_u, u = heapq.heappop(heap)
        if dist_u != distances[u]:
            continue
        if u == dest:
            return dist_u
        for v, dist_uv in wgraph[u].items():
            if ((period := blocked_period.get((u, v))) and
                    period[0] <= dist_u < period[1]):
                dist_v = period[1] + dist_uv
            else:
                dist_v = dist_u + dist_uv
            if dist_v < distances[v]:
                distances[v] = dist_v
                heapq.heappush(heap, (dist_v, v))


def main():
    N, M = [int(x) for x in sys.stdin.readline().split()]
    wgraph = [{} for _ in range(N)]
    # pylint: disable=unused-variable
    A, B, K, G = [int(x) for x in sys.stdin.readline().split()]
    route = [int(x) for x in sys.stdin.readline().split()]
    for _ in range(M):
        U, V, L = [int(x) for x in sys.stdin.readline().split()]
        wgraph[U - 1][V - 1] = wgraph[V - 1][U - 1] = L

    blocked_period = {}
    beg = -K
    for u, v in itertools.pairwise(route):
        end = beg + wgraph[u - 1][v - 1]
        blocked_period[u - 1, v - 1] = blocked_period[v - 1, u - 1] = (beg, end)
        beg = end

    print(dijkstra(wgraph, blocked_period, A - 1, B - 1))


if __name__ == '__main__':
    main()