Problem 509560 · hard · Phase 05 Advanced Algorithms & Graphs

One Free Toll Pass

graphs · Dijkstra · state space · layered graph

A driver crosses a toll network with n junctions 0 .. n-1 and undirected toll roads roads[i] = [u, v, toll] (toll >= 0). They hold a single free pass that waives the toll of one road of their choice (or they may not use it at all).

Return the minimum total toll from src to dst, or -1 if dst is unreachable.

Examples

Input:  n = 4, roads = [[0,1,10],[1,3,1],[0,2,3],[2,3,4]], src = 0, dst = 3
Output: 1
Explanation: use the pass on 0-1 (toll 10) and pay 1 for 1-3.

Input:  n = 3, roads = [[0,1,5]], src = 0, dst = 2
Output: -1

Constraints

  • 1 <= n <= 10**4, 0 <= len(roads) <= 3 * 10**4, 0 <= toll <= 10**5
  • Target O(E log V) time.

Goals

  • Extend the Dijkstra state with 'pass used or not'
  • Offer two transitions per edge from the unused layer
  • Take the best over both layers at the destination
Starting Python…