Music streaming app~40 min2s · 256 MBtarget O((n + m) log (n + m)) time, O(n + m) spaceclassic twin: lc-1168union-find
A video service has n cache servers, and every server must end up with the content. A server can get its own uplink to the origin, which has a cost. Or it can copy from another server over a link, which also has a cost.
Several plans can cost the same. Uplinks use origin bandwidth, so among the cheapest plans the team prefers the one with the fewest uplinks.
You find the lowest total cost, and the fewest uplinks that cost achieves.
Write cheapest_relay_plan(uplink, links).
uplink[i] is the cost of an uplink from the origin to server i. The servers are numbered 0 to n - 1, where n = len(uplink).links[j] is [a, b, cost]: servers a and b can be joined by a link of that cost, and content can flow either way.[total, uplinks]: the lowest total cost, and the fewest uplinks among all plans with that total.Input: uplink = [5,4,6,4], links = [[0,1,2],[1,2,3],[2,3,4],[0,3,10]]
Output: [13,1]The solution adds a virtual origin node, and treats every uplink as a link from the origin to its server. It sorts all links by cost, with a normal link before an uplink of the same cost. Then it keeps every link that joins two groups.
| Link | Kind | Cost | Joins two groups | Total | Uplinks |
|---|---|---|---|---|---|
| servers 0 and 1 | link | 2 | yes | 2 | 0 |
| servers 1 and 2 | link | 3 | yes | 5 | 0 |
| servers 2 and 3 | link | 4 | yes | 9 | 0 |
| origin and server 1 | uplink | 4 | yes | 13 | 1 |
| origin and server 3 | uplink | 4 | no, already joined | 13 | 1 |
The remaining links are skipped. The lowest total is 13 with 1 uplink.
Input: uplink = [5,4,6,4], links = []
Output: [19,4]There are no links, so every server needs its own uplink: 5 + 4 + 6 + 4 = 19 with 4 uplinks.
Input: uplink = [7,7], links = [[0,1,7]]
Output: [14,1]One plan buys two uplinks for 14. Another buys one uplink and the link, also for 14. The second plan has fewer uplinks, so the answer is [14,1].
1 ≤ len(uplink) ≤ 100,000, and 1 ≤ uplink[i] ≤ 1,000,0000 ≤ len(links) ≤ 100,000, and every link is [a, b, cost] with 0 ≤ a, b < n and 0 ≤ cost ≤ 1,000,000A plan is a choice among up to 200,000 connections, and the number of choices grows faster than any power of 200,000. Sorting the connections once costs about 200,000 times 18 steps, which is 3,600,000.