Problem Description
Given n cities connected by highways, each with a specified toll, you need to find the minimum cost to travel from city 0 to city n - 1. You also have a number of discounts available, where a discount lets you traverse a highway at half its toll cost (using integer division). Each highway can use at most one discount and each discount can only be used once. If it is not possible to reach city n - 1, return -1.
Key Insights
- This is a shortest path problem on an undirected weighted graph.
- The twist is the limited number of discounts that can be applied, which leads to an augmented state-space.
- Each state can be represented by (city, discountsUsed), and we need to track the cost accordingly.
- A modified Dijkstra's algorithm can be applied by taking into consideration whether to use a discount on a given edge.
- The challenge is to consider both scenarios: using a discount (if available) and not using one when transitioning between cities.
Space and Time Complexity
Time Complexity: O(highways.length * (discounts + 1) * log(n * (discounts + 1))) Space Complexity: O(n * (discounts + 1)) for the distance/state tracking structure.
Solution
We solve the problem using a modified Dijkstra's algorithm, which tracks an augmented state defined by the current city and the number of discounts used so far. A min-heap (priority queue) is used, where each element is (currentCost, currentCity, usedDiscounts). For every neighboring city of the current state, we explore two possibilities:
- Traverse the edge without applying a discount.
- Traverse the edge with a discount (provided we still have discounts remaining). The distance table is updated for every state, and the process continues until either the destination is reached or all states are processed.