Problem Description
Given a weighted directed graph with n nodes numbered from 0 to n-1 and a list of directed edges with their weights, find a subgraph (a subset of the original edges) that allows both src1 and src2 to reach dest. The objective is to minimize the sum of weights of the selected edges. If no such subgraph exists, return -1.
Key Insights
- The problem essentially requires two paths: one from src1 to dest and one from src2 to dest.
- Instead of independently finding two paths, we can leverage the observation that there exists an intermediate node v such that:
- There is a shortest path from src1 to v.
- There is a shortest path from src2 to v.
- And there is a shortest path from v to dest.
- By reversing the graph, the path from any node v to dest in the original graph becomes a path from dest to v in the reversed graph.
- Running three instances of Dijkstra's algorithm (from src1, from src2, and from dest on the reversed graph) gives the minimum distance from the respective source nodes to every other node.
- The answer is the minimum over all nodes v of (dist(src1, v) + dist(src2, v) + dist(v, dest)). If any part is unreachable for a given v, skip that candidate.
Space and Time Complexity
Time Complexity: O(E log N), where E is the number of edges and N is the number of nodes because Dijkstra's algorithm is run three times. Space Complexity: O(N + E) for the graph representation and distance arrays.
Solution
To solve the problem, we use Dijkstra's algorithm three times:
- From src1 on the original graph to get distances from src1 to every node.
- From src2 on the original graph to get distances from src2 to every node.
- From dest on the reversed graph to get distances from every node to dest. For each node v, we calculate totalCost = dist1[v] + dist2[v] + dist3[v] (where dist3[v] is the distance from v to dest calculated on the reversed graph). The answer is the minimum totalCost among all nodes v that are reachable from the respective sources. If no such candidate exists, we return -1.