Minimum Weighted Subgraph With the Required Paths
Real-world version: The Cheapest Shared Route to the DepotThe statement here is our own: the same inputs, outputs and technique.
A network has n yards numbered 0 through n - 1, joined by the one-way roads roads, where roads[i] = [a, b, w] runs from yard a to yard b and costs w to lay.
Choose a set of roads to lay so that the depot at depot can be reached from from1 by following laid roads, and likewise from from2. A laid road is paid for once however many journeys use it.
Return the smallest total cost, or -1 when no set of roads manages it. The three named yards are all different.
Examples
Example 1
- Input
- n = 5, roads = [[0, 4, 10], [1, 4, 10], [0, 2, 1], [1, 2, 1], [2, 4, 1]], from1 = 0, from2 = 1, depot = 4
- Output
- 3
Both starting yards can run straight to the depot for ten apiece, twenty in all. Joining at yard 2 instead costs one from each starting yard and one more from there to the depot, three altogether, since the last stretch is paid for once.
Example 2
- Input
- n = 3, roads = [[0, 2, 5], [1, 2, 7]], from1 = 0, from2 = 1, depot = 2
- Output
- 12
The two journeys share nothing, so they meet only at the depot itself, and the two roads there cost five and seven.
Example 3
- Input
- n = 3, roads = [], from1 = 0, from2 = 1, depot = 2
- Output
- -1
There are no roads at all, so the depot cannot be reached from anywhere.
Constraints
- 3 <= n <= 10^5
- 0 <= roads.length <= 10^5
- roads[i].length == 3
- 0 <= roads[i][0] <= n - 1
- 0 <= roads[i][1] <= n - 1
- 1 <= roads[i][2] <= 10^5
- The two ends of a road are different yards.
- from1, from2 and depot are three different yards.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def minimum_weight(n: int, roads: list[list[int]], from1: int, from2: int, depot: int) -> int:public long minimumWeight(int n, int[][] roads, int from1, int from2, int depot)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Cheapest Flights Within K StopsReal-world version: Limited Handoff Courier RouteMedium
- Network Delay TimeReal-world version: Relay Broadcast TimeMedium
- Find a Safe Walk Through a GridReal-world version: Shielded Crossing of a Scorched Bay FloorMedium
- Path with Maximum ProbabilityReal-world version: Most Reliable Parcel RouteMedium