Parcel-delivery app~30 min2s · 256 MBtarget O(n²) time, O(n) spaceclassic twin: lc-1584greedy · union-find
A parcel-delivery app has depots on a city grid. Depot i sits at the point (xs[i], ys[i]). A link between two depots costs the Manhattan distance: the difference in x plus the difference in y.
The company wants every depot to reach every other depot through links. Some pairs are already linked, and those links are free. It wants to pay as little as possible for the new links.
Write cheapest_links(xs, ys, built).
xs and ys have the same length. The depot i is at (xs[i], ys[i]).built[j] is [a, b], a link between depots a and b that already exists. It costs nothing, and a link works in both directions.Input: xs = [0,2,3,5,7], ys = [0,2,10,3,0], built = []
Output: 22The solution grows one tree from depot 0. For every depot outside the tree it keeps the cheapest link to the tree. It adds the cheapest one each time.
| Step | Depot added | Cost | Cheapest links for depots 1, 2, 3, 4 |
|---|---|---|---|
| start | 0 | 0 | 4, 13, 8, 7 |
| 1 | 1 | 4 | -, 9, 4, 7 |
| 2 | 3 | 4 | -, 9, -, 5 |
| 3 | 4 | 5 | -, 9, -, - |
| 4 | 2 | 9 | all in the tree |
The total is 4 + 4 + 5 + 9 = 22.
Input: xs = [0,2,3,5,7], ys = [0,2,10,3,0], built = [[2,3]]
Output: 13Depot 2 is already linked to depot 3, so it joins the tree with depot 3 at no cost. The new links cost 4, 4 and 5.
Input: xs = [4], ys = [4], built = []
Output: 0One depot needs no links.
1 ≤ len(xs) = len(ys) ≤ 1,0000 ≤ xs[i], ys[i] ≤ 100,0000 ≤ len(built) ≤ 1,000, and each depot number is from 0 to len(xs) - 1Any two depots can be linked, so there are about 500,000 possible links. A search that scans every pair for each link added takes about 1,000 × 500,000 steps, which is 500,000,000. Growing a tree from one depot costs about 1,000 × 1,000 steps.