Dodomeki
Sign in

158. The Toll Road

Hard

A network of cities is connected by two-way roads. Each road has a travel time, and each city charges a toll whenever you pass through it. The toll for the starting city is charged once at the beginning of the trip; the destination city's toll is charged as well. If a route visits a city again, its toll is charged again.

You are given pedagios, where pedagios[i] is the toll charged by city i, estradas, where each road is represented by [a, b, tempo], and limite, the maximum allowed travel time. The trip starts at city 0 and ends at city n - 1, where n is the length of pedagios.

Return the minimum total toll among routes whose total travel time is at most limite. If no valid route exists, return -1.

Example 1
Input: pedagios = [5, 2, 4, 1], estradas = [[0, 1, 3], [1, 3, 4], [0, 2, 2], [2, 3, 7]], limite = 7
Output: 8
Explanation: The route 0 → 1 → 3 takes 7 time units and costs 5 + 2 + 1.
Example 2
Input: pedagios = [3, 8, 2], estradas = [[0, 1, 2], [1, 2, 2], [0, 2, 5]], limite = 5
Output: 5
Explanation: The direct road takes 5 time units and charges the tolls for cities 0 and 2.
Example 3
Input: pedagios = [1, 2, 3], estradas = [[0, 1, 2], [1, 2, 2]], limite = 3
Output: -1
Explanation: The only route to city 2 takes 4 time units, which exceeds the limit.
Constraints
  • 1 <= pedagios.length <= 1000
  • 0 <= pedagios[i] <= 10^9
  • 0 <= estradas.length <= 5000
  • Each road has the form [a, b, tempo], where 0 <= a, b < pedagios.length and a != b.
  • 1 <= tempo <= 5000
  • 0 <= limite <= 5000
GraphsHeapDynamic programming
Caso 1
pedagios =
[5,2,4,1]
estradas =
[[0,1,3],[1,3,4],[0,2,2],[2,3,7]]
limite =
7
Expected =
8
Caso 2
pedagios =
[3,8,2]
estradas =
[[0,1,2],[1,2,2],[0,2,5]]
limite =
5
Expected =
5
Caso 3
pedagios =
[1,2,3]
estradas =
[[0,1,2],[1,2,2]]
limite =
3
Expected =
-1

Run checks these 3 cases. Submit runs all 12, including hidden ones.