Parcel-delivery app~30 min2s · 256 MBtarget O(n) time, O(n) spacetree-recursion
You work on a parcel-delivery app. A region has n towns joined by roads so that there is exactly one route between any two towns. Each town has a daily demand for parcels, and each road has a length in kilometres.
The company will build one depot in a town. Every day, each town's parcels travel from the depot along the only route. Your team lead asks: "Which town gives the smallest total of demand times distance, and what is that total?" The region can hold 100,000 towns.
Write best_depot(demands, links, lengths).
demands[i] is the daily demand of town i. Towns are numbered 0 to n - 1.links[j] = [a, b] is a road between towns a and b, and lengths[j] is its length. There are exactly n - 1 roads, and every town can reach every other.d is the sum, over all towns t, of demands[t] times the route length from d to t.[town, cost]: the best town and its cost. If several towns have the same lowest cost, return the one with the smallest number.Input: demands = [2, 0, 5, 1, 4], links = [[0, 1], [1, 2], [1, 3], [3, 4]], lengths = [3, 2, 4, 1]
Output: [1, 40]| Depot in town | Cost |
|---|---|
| 0 | 2×0 + 0×3 + 5×5 + 1×7 + 4×8 = 64 |
| 1 | 2×3 + 0×0 + 5×2 + 1×4 + 4×5 = 40 |
| 2 | 44 |
| 3 | 48 |
| 4 | 52 |
Town 1 has the lowest cost, 40.
Input: demands = [7], links = [], lengths = []
Output: [0, 0]Input: demands = [1, 1], links = [[0, 1]], lengths = [5]
Output: [0, 5]Both towns cost 5, so the smaller number wins.
1 ≤ n ≤ 100,000, where n = len(demands).len(links) = len(lengths) = n - 1, and the roads form one tree.0 ≤ demands[i] ≤ 1001 ≤ lengths[j] ≤ 1,000Computing the cost for every depot with its own walk takes about 10,000,000,000 steps, because each walk visits all 100,000 towns. The cost for one town differs from the cost of a neighbouring town by a simple amount. The costs of all 100,000 towns can come from one walk and one correction per road, about 300,000 steps.