Ctrl K

Toll Roads with Free Passes

Hard
A country has n cities numbered 0 to n - 1 and two-way toll roads: roads[i] = [a, b, cost] connects cities a and b, and driving along it costs cost. Every city can reach every other, there is at most one road between any two cities, and no road leads from a city to itself. A traveller holds passes passes. A pass makes one road free, and a route may use at most passes of them. Return the smallest amount the traveller has to pay to get from city start to city finish.
Example 1
n=4, roads=[[0, 1, 5], [1, 3, 5], [0, 2, 1], [2, 3, 20]], start=0, finish=3, passes=1 → 1

Without passes the best route is 0 → 1 → 3 for 10. With one pass, 0 → 2 → 3 is cheaper: pay 1 for the first road and ride the road worth 20 for free.

Example 2
n=3, roads=[[0, 1, 7], [1, 2, 3]], start=0, finish=2, passes=0 → 10

There are no passes and only one route: 7 + 3 = 10.

Example 3
n=5, roads=[[0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 4, 4]], start=0, finish=4, passes=2 → 8

The route 0 → 1 → 2 → 3 → 4 has four roads worth 4 each; two are free, which leaves 8.

Constraints
  • 2 ≤ n ≤ 500
  • n − 1 ≤ roads.length ≤ min(10⁴, n·(n − 1)/2)
  • 0 ≤ a, b ≤ n − 1, a ≠ b
  • 1 ≤ cost ≤ 10⁶
  • 0 ≤ start, finish, passes ≤ n − 1, start ≠ finish
  • The graph is connected and has no repeated roads
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBall Into the Hole HardCheckpoints Within Reach HardRepaint Arrows to Reach the Exit HardThrough the Walls to the Far Corner HardRooms on a Timer Hard
loading Python…
Input
n=4, roads=[[0, 1, 5], [1, 3, 5], [0, 2, 1], [2, 3, 20]], start=0, finish=3, passes=1
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 62 tests on the server, hidden ones included.