This problem asks for the minimum cost to travel from city 0 to city n-1 using a given set of highways and a limited number of discounts. The discounts allow you to halve the cost of a highway's toll.
The solution uses Dijkstra's algorithm with a key modification to handle the discounts. Instead of a single distance array to track the minimum cost to reach each city, we use a 2D array dist[i][k]
, where i
represents the city and k
represents the number of discounts used so far.
Algorithm:
Graph Representation: The highways
array is transformed into an adjacency list graph g
, where each node represents a city, and edges represent the highways with their tolls.
Initialization: A priority queue q
is used to store (cost, city, discounts_used) tuples, ordered by cost. The dist
array is initialized to infinity. The algorithm starts by adding (0, 0, 0) to the queue, representing a cost of 0 to reach city 0 using 0 discounts.
Dijkstra's Algorithm: The algorithm iteratively extracts the minimum-cost tuple from the queue. If the city has already been visited with a lower cost or more discounts, it's skipped.
Discount Application: For each neighbor of the current city, two tuples are added to the queue: one with the full toll and the current discount count, and another with the halved toll and the discount count incremented. This explores all possible uses of discounts.
Termination: The algorithm terminates when the destination city (n-1) is reached, returning the minimum cost. If the queue is empty before reaching the destination, it means there is no path, and -1 is returned.
Time Complexity Analysis:
The priority queue operations (insertion and extraction) take O(log(E*D)), where E is the number of edges (highways) and D is the number of discounts + 1. The algorithm iterates through at most all edges and nodes. Therefore, the overall time complexity is O(E * D * log(E * D)). In the worst case, where every edge is explored with every possible discount combination, this bound becomes relevant.
Space Complexity Analysis:
The space complexity is dominated by the dist
array, which has dimensions n x (discounts + 1), and the priority queue, which stores at most E * D elements. Therefore, the overall space complexity is O(n * D + E * D), which simplifies to O(n*D) as n is typically smaller than E in this context.
Code in different languages:
The provided code snippets in Python, Java, and C++ implement this algorithm efficiently. They all use a priority queue (heap) to achieve the optimal time complexity for Dijkstra's algorithm. The key differences lie primarily in the syntax and data structures of each language, but the underlying logic remains the same.