Chat app~30 min2s · 256 MBtarget O(n^3 + q x n^2) time, O(n^2) spaceshortest-paths
A messaging service links its shards, numbered from 0, with two-way links. Each link has a latency in milliseconds. A message can pass through other shards, and its latency is the sum of the links it uses.
Operators add new links one at a time. After the starting links, and after each added link, they record a health figure. It is the sum of the shortest latencies over all connected pairs of shards. Pairs with no route are left out.
Write totals_after_links(n, links, extra).
n shards, numbered from 0 to n - 1.links[i] is [a, b, ms]: a two-way link of ms milliseconds. Two links may join the same pair, and ms may be 0.extra[i] has the same form. These links are added one at a time, in order, to the starting links.len(extra) + 1 totals: the total for the starting links, then the total after each added link.Input: n = 4, links = [[0,1,5],[1,2,5]], extra = [[0,2,3],[2,3,2]]
Output: [20, 13, 27]At the start, shards 0, 1 and 2 are connected and shard 3 stands alone. The pairs have latencies 5, 10 and 5. Adding the link 0 to 2 makes that pair 3. Adding the link 2 to 3 connects shard 3 to the rest, and three new pairs appear.
The solution keeps the whole table of latencies. A route from i to j may use the new link between a and b. It goes from i to a, over the link, then from b to j, or the other way round.
| Step | Link added | Pairs and shortest latencies | Total |
|---|---|---|---|
| start | none | 0-1: 5, 0-2: 10, 1-2: 5 | 20 |
| 1 | 0-2 in 3 ms | 0-1: 5, 0-2: 3, 1-2: 5 | 13 |
| 2 | 2-3 in 2 ms | 0-1: 5, 0-2: 3, 0-3: 5, 1-2: 5, 1-3: 7, 2-3: 2 | 27 |
The total can rise, as in step 2, when a link connects a shard that was alone.
Input: n = 2, links = [[0,1,4]], extra = []
Output: [4]There is nothing to add, so the list has one total: the single pair at 4 ms.
Input: n = 3, links = [], extra = [[0,1,1],[1,2,1],[0,2,5]]
Output: [0, 1, 4, 4]At first no pair is connected, so the total is 0. The links 0 to 1 and 1 to 2 give pairs at 1, 1 and 2. The link 0 to 2 at 5 ms is slower than the route through shard 1, so nothing changes.
1 ≤ n ≤ 800 ≤ links.length ≤ 1,500 and 0 ≤ extra.length ≤ 200[a, b, ms] with 0 ≤ a, b < n, a ≠ b and 0 ≤ ms ≤ 10,000Rebuilding every shortest latency after each added link costs n^3 per rebuild. For 80 shards and 200 added links that is 200 × 512,000 = 10^8 steps. Updating the table in place costs n^2 per link, 200 × 6,400 = 1.3 × 10^6 steps, plus one n^3 build at the start.