Monitoring~25 min2s · 256 MBtarget O(n^3) time, O(n^2) spaceclassic twin: lc-1334shortest-paths
A monitoring team studies a cluster of services, numbered from 0. Two services may be joined by a two-way link with a latency in milliseconds. A message can pass through other services on the way, and its latency is the sum of the links it uses.
A service is a peer of another when the fastest route between them takes at most a latency budget. The team wants the service with the fewest peers, because it is the least connected. If several services tie, they want the one with the largest id.
Write quietest_service(n, links, budget).
n services, numbered from 0 to n - 1.links[i] is [a, b, ms]: a two-way link of ms milliseconds between different services. Two links may join the same pair.x is a service whose latency from x is at most budget.Input: n = 5, links = [[0,2,3],[0,4,4],[1,3,2],[1,4,2],[2,3,1],[3,4,4]], budget = 5
Output: 1Routes may use several links. Service 0 reaches service 3 through service 2 in 3 + 1 = 4 ms. The table lists, for each service, the peers within 5 ms.
| Service | Peers within 5 ms | Count |
|---|---|---|
| 0 | 2, 3, 4 | 3 |
| 1 | 2, 3, 4 | 3 |
| 2 | 0, 1, 3, 4 | 4 |
| 3 | 0, 1, 2, 4 | 4 |
| 4 | 0, 1, 2, 3 | 4 |
Services 0 and 1 have the fewest peers, 3 each. The tie goes to the larger id, so the answer is 1.
Input: n = 3, links = [], budget = 5
Output: 2No service has a peer. All three tie with 0 peers, and the largest id is 2.
Input: n = 2, links = [[0,1,5]], budget = 4
Output: 1The only link takes 5 ms, which is over the budget. Both services have 0 peers, so the larger id wins.
1 ≤ n ≤ 1000 ≤ links.length ≤ 4,950, and each link is [a, b, ms] with 0 ≤ a, b < n, a ≠ b and 1 ≤ ms ≤ 10,0000 ≤ budget ≤ 1,000,000Walking every route without repeating a service can mean a number of routes that grows faster than any power of n. For a complete graph of 100 services that is beyond reach. Floyd-Warshall tries each service as a stop for each pair, which costs n^3 = 10^6 steps.