Monitoring~30 min2s · 256 MBtarget O(n^3 + q × n^2) time, O(n^2) spaceshortest-paths
You work on an observability platform. A cluster has n services, numbered 0 to n - 1, joined by two-way links. Each link has a latency in microseconds, and the first links connect every service to every other one, possibly through other services.
The latency between two services is the smallest total latency over the links of any route between them. Operators bring new links online one at a time, and a new link never removes an old one.
Your team lead asks: "After each new link, what is the sum of the latencies over all pairs of services?" The cluster has at most 100 services and 100 new links.
Write latency_totals(n, links, added).
links[k] = [a, b, w] is a two-way link between services a and b with latency w. The links connect all n services. Links can repeat, and a can equal b.added[k] = [a, b, w] is the k-th new link, in the same format. Every new link stays online after it appears.Input: n = 4, links = [[0, 1, 5], [1, 2, 5], [2, 3, 5]], added = [[0, 3, 7], [0, 2, 3]]
Output: [42, 35]Four services sit on a chain. The lowest latency of every pair, at the start and after each new link:
| Pair | Start | After link 1 | After link 2 |
|---|---|---|---|
| 0–1 | 5 | 5 | 5 |
| 0–2 | 10 | 10 | 3 |
| 0–3 | 15 | 7 | 7 |
| 1–2 | 5 | 5 | 5 |
| 1–3 | 10 | 10 | 10 |
| 2–3 | 5 | 5 | 5 |
| Sum | 50 | 42 | 35 |
The sums are the answers: 42 after the first link and 35 after the second.
Input: n = 2, links = [[0, 1, 4]], added = [[0, 1, 2], [0, 1, 9]]
Output: [2, 2]The first new link is faster than the old one, and the second is slower, so it changes nothing.
Input: n = 1, links = [], added = [[0, 0, 5]]
Output: [0]One service has no pair, so the sum is 0.
1 ≤ n ≤ 1000 ≤ len(links) ≤ 1,000, and the links connect all n services0 ≤ len(added) ≤ 1000 ≤ a, b < n, and 1 ≤ w ≤ 1,000,000 for every linkA table with the distance of every pair has only 10,000 entries, and a full computation costs about 1,000,000 steps. But doing it again after each of 100 new links costs 100 million steps. One new link changes the pairs only through its own two ends, which a single pass over the table can handle.