Official

D - 山岳ハイキング / Mountain Hiking Editorial by sounansya


疲労度が \(K\) 以下の辺のみを考えたグラフでダイクストラ法を用いて最短距離を計算すれば良いです。

実装例(Python3)

import heapq

input = __import__("sys").stdin.readline

INF = 10**18


def dijkstra(edges, start_node: int) -> list:
    hq = []
    heapq.heapify(hq)
    dist = [INF] * len(edges)
    heapq.heappush(hq, (0, start_node))
    dist[start_node] = 0
    while hq:
        min_cost, now = heapq.heappop(hq)
        if min_cost > dist[now]:
            continue
        for cost, next in edges[now]:
            if dist[next] > dist[now] + cost:
                dist[next] = dist[now] + cost
                heapq.heappush(hq, (dist[next], next))
    return dist


n, m, k = map(int, input().split())
h = list(map(int, input().split()))
g = [[] for _ in range(n)]
for i in range(m):
    u, v = map(int, input().split())
    u, v = u - 1, v - 1
    c = abs(h[u] - h[v])
    if c > k:
        continue
    g[u].append((c, v))
    g[v].append((c, u))
d = dijkstra(g, 0)
ans = d[-1]
print(-1 if ans == INF else ans)

posted:
last update: