Chat app~30 min2s · 256 MBtarget O((n + m) log n) time, O(n + m) spaceclassic twin: lc-1514dijkstra
A messaging app relays a message from one server to another through two-way links. Each link delivers the message with a percent chance from 1 to 100.
A route delivers the message only if every link does, so its chance is the product of the link chances. The app stores a chance as a whole number of parts out of one billion. After crossing a link with p percent it keeps p hundredths of the parts, rounded down. The team wants the route with the best chance.
Write best_delivery_chance(n, links, source, target).
0 to n - 1. links[i] = [a, b, percent] is a two-way link that delivers with percent percent, from 1 to 100. A pair may have several links.source with 1,000,000,000 parts. Crossing a link with percent turns parts into parts * percent // 100, rounded down.target over all routes.1,000,000,000 when source equals target, and -1 when no route exists. A route that exists but rounds down to 0 parts returns 0.Input: n = 5, links = [[0, 1, 90], [1, 2, 90], [0, 2, 70], [2, 3, 80], [1, 3, 60], [3, 4, 95]], source = 0, target = 4
Output: 615600000The solution is Dijkstra's algorithm that takes the server with the highest chance first. Crossing a link can only keep or lower the chance, so a server taken first is final.
| Server taken | Best chance (parts out of one billion) |
|---|---|
| 0 | 1,000,000,000 |
| 1 | 900,000,000 |
| 2 | 810,000,000 |
| 3 | 648,000,000 |
| 4 | 615,600,000 |
The best route to server 4 is 0, 1, 2, 3, 4. It has more links than the direct route through server 2 and server 3, but its links are more reliable.
Input: n = 2, links = [[0, 1, 95]], source = 0, target = 1
Output: 950000000One link of 95 percent leaves 950,000,000 parts.
Input: n = 3, links = [[0, 1, 50]], source = 0, target = 2
Output: -1No link reaches server 2.
1 ≤ n ≤ 5,000, and 0 ≤ len(links) ≤ 20,000links[i] = [a, b, percent] with 0 ≤ a, b < n and 1 ≤ percent ≤ 1000 ≤ source, target < nA route can have thousands of links, so trying all routes is impossible. Repeated sweeps over all 20,000 links, which stop when nothing changes, can need about one sweep for each server, which is 100,000,000 steps. A heap-based search handles each link a couple of times, with about 520,000 steps.