CSES - Investigation
Problem Link
Time Complexity: O(N + M log M)
Algorithm used: Dijkstra, DP (partly)
The problem statement is quite straightforward: a series of M one-way flight routes are described, each connecting one city to another city and having a cost. You want to travel from city 1 to city N. Find:
- minimum price of such a route
- the number of minimum-price routes
- maximum number of flights in a minimum-price route
- minimum number of flights in a maximum-price route
This can be modelled as a graph problem, where the cities are the nodes and the flights are the edges. Each flight has a cost and only travels in one direction, so the graph is weighted and directed. A minimum price route to node N means the shortest path to node N.
Since the route must start from city 1 and the edges are weighted, some form of Dijkstra's algorithm must be applied. The key point is to collect the data for the 4 answers while running the Dijkstra's.
Maintain 4 arrays: one for the shortest path to reach node i (dis), one for the number of ]shortest paths to node i (sp), one for the minimum number of flights on a shortest path to node i (min_flight) and one for the maximum number of flights on a shortest path to node i (max_flight).
While running Dijkstra's, if we come across a shorter path to node i than any other path that we have come across till now, we need to update the 4 arrays.
- The length of the shortest path to i can be updated as done in standard Dijkstra's.
- the number of shortest paths is updated to 1, since this is the first time a route of this length has been found.
- the minimum number of nodes traversed by the shortest path to this node is the minimum number of nodes traversed by the shortest path to the parent city + 1 (add 1 to account for the current city).
- the maximum number of nodes traversed by the shortest path to this node is the minimum number of nodes traversed by the shortest path to the parent city + 1 (add 1 to account for the current city).
- The length of the shortest path remains the same, so no need to update this array.
- The number of shortest paths increases by 1 (while adding a path, modulo the sum by 10⁹ + 7).
- the minimum number of nodes traversed by the shortest path to reach node i could be the previous minimum calculated or the number of nodes traversed by the current shortest path. So, the answer is the minimum of the two.
- the maximum number of nodes traversed by the shortest path to reach node i could be the previous maximum calculated or the number of nodes traversed by the current shortest path. So, the answer is the maximum of the two.
Comments