Collect Coins in a Tree
Real-world version: Shortest Round Trip to Sweep Every ParcelThe statement here is our own: the same inputs, outputs and technique.
A network of hubs is given as a tree: edges lists the links, and coins[i] is 1 when hub i holds a parcel and 0 otherwise.
A van starts at any hub it likes and must finish back where it started. A parcel is swept when the van visits some hub no more than two links away from the parcel's hub.
Every link travelled counts, and travelling the same link again counts again. Return the fewest links the round trip can travel while sweeping every parcel.
Examples
Example 1
- Input
- coins = [1, 0, 0, 1], edges = [[0, 1], [1, 2], [2, 3]]
- Output
- 0
The hubs run in a line of four with parcels at the two ends. Standing at either middle hub sweeps both ends, since each is within two links, so the van need not move at all.
Example 2
- Input
- coins = [1, 0, 0, 0, 0, 0, 0, 1], edges = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]]
- Output
- 6
The line is eight hubs long with parcels at the ends. The van must reach within two links of each end, which means covering the two middle links and walking them both ways.
Example 3
- Input
- coins = [0], edges = []
- Output
- 0
A single hub with no parcel means there is nothing to sweep.
Constraints
- 1 <= coins.length <= 3 * 10^4
- 0 <= coins[i] <= 1
- edges.length == coins.length - 1
- edges[i].length == 2
- 0 <= edges[i][0] <= coins.length - 1
- 0 <= edges[i][1] <= coins.length - 1
- The two hubs on a link are different
- The links form a tree
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 collect_the_coins(coins: list[int], edges: list[list[int]]) -> int:public int collectTheCoins(int[] coins, int[][] edges)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 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
- Longest Path With Different Adjacent CharactersReal-world version: The Longest Run of Unlike PostsHard
- Find All Possible Recipes from Given SuppliesReal-world version: Fabrication Cards in a Model WorkshopMedium
- Loud and RichReal-world version: Steadiest Hand in the WorkshopMedium
- Apply SubstitutionsReal-world version: Render A Config TemplateMedium