Minimum Cost to Buy Apples II
Real-world version: Cheapest Round Trip for One CrateThe statement here is our own: the same inputs, outputs and technique.
A region has n depots numbered from 0, and depot i sells a crate for prices[i].
Each entry of roads is [u, v, cost, tax] for a two-way road. Driving that road outward costs cost, and driving it back costs cost * tax.
Starting from a depot, you drive to any depot, buy exactly one crate there, and drive home along the very same roads you came by. Buying at home is allowed and costs no driving at all.
Return, for each depot in turn, the least a round trip can cost.
Examples
Example 1
- Input
- n = 4, prices = [27, 9, 41, 14], roads = [[0, 1, 3, 2], [1, 2, 4, 1], [2, 3, 2, 3]]
- Output
- [18, 9, 17, 14]
Each road is worth its cost times one more than its tax, so the three roads weigh 9, 8 and 8. From depot 0 the cheapest trip drives to depot 1 for 9 and buys at 9, coming to 18, which beats buying at home for 27.
Example 2
- Input
- n = 2, prices = [5, 100], roads = []
- Output
- [5, 100]
With no roads at all, every depot can only buy at home.
Example 3
- Input
- n = 3, prices = [10, 10, 10], roads = [[0, 1, 1, 100], [1, 2, 1, 100]]
- Output
- [10, 10, 10]
Every depot sells at the same price and the roads are heavily taxed, so no trip beats buying at home.
Constraints
- 1 <= n <= 1000
- prices.length == n
- 1 <= prices[i] <= 10^9
- 0 <= roads.length <= 2000
- roads[i].length == 4
- 0 <= roads[i][0] <= n - 1
- 0 <= roads[i][1] <= n - 1
- The two depots on a road are different
- 1 <= roads[i][2] <= 10^9
- 1 <= roads[i][3] <= 100
- No road is listed twice
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 min_cost(n: int, prices: list[int], roads: list[list[int]]) -> list[int]:public int[] minCost(int n, int[] prices, int[][] roads)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 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
- 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
- Network Recovery PathwaysReal-world version: Fibre Restoration GradeHard
- Minimum Cost to Make at Least One Valid Path in a GridReal-world version: Cheapest Rewiring Of Conveyor ArrowsHard