Opening your workspace…
Workspace/Coding room
Opening your workspace…
The brewery post snail has worn a hole in her second-best boot. Pick a stop for her depot that makes the day's deliveries cost as little as possible. The stops form a tree rooted at 0 with parent[0] = -1. Every other stop i joins parent[i] by a two-way path of length lengths[i]. Parents can have larger indices than their children. Stop i needs demand[i] deliveries, each costing the distance along the tree from the depot to i. Deliveries at the depot itself cost zero. Return [hubIndex, minimumCost]. If several stops tie, the snail takes the one with the smallest index.
[-1,0,0], [0,2,1], [0,3,1]Output[1,3]With the hub at node 1, only the delivery to node 2 has to travel, along a path of length 2 + 1 = 3. A hub at node 0 would cost 7 and a hub at node 2 would cost 9.
[-1,0], [0,4], [2,2]Output[0,8]A hub at either node costs 2 times 4 = 8, so the answer is the smaller index, 0.
First work out the cost of a hub at node 0 and the total demand inside each subtree. Then move the hub across one link at a time: the deliveries in that child's subtree get closer by the length of the link, and all the others get farther away by the same amount.
Practice bottom-up subtree accumulation before adding a reroot pass.
Try this problem →Class B · Trees / Breadth-first searchBuild confidence traversing a parent-array tree without recursive calls.
Try this problem →/** @param {number[]} parent * @param {number[]} lengths * @param {number[]} demand * @returns {number[]} */ function solve(parent, lengths, demand) { // Return the best hub and its total cost. }
Tab inserts two spaces. Shift+Tab outdents. Use the arrow keys and Tab to choose a suggestion. Press Escape, then Tab, to leave the editor. Press Control or Command with apostrophe to run samples or with Enter to submit.
[-1,0,0], [0,2,1], [0,3,1][1,3]