Parcel-delivery app~40 min2s · 256 MBtarget O((m log m + q log q) α(n)) time, O(n + q) spaceclassic twin: lc-1697union-find
A parcel-delivery app plans truck routes across towns. Each road has a load limit: a truck can use the road only if its load is at most the limit. A truck can go along any chain of roads.
Dispatchers ask many questions of the same road network. For a pair of towns, what is the heaviest load a truck can carry from one to the other? Roads work in both directions.
Write max_loads(towns, roads, queries).
towns is the number of towns, numbered 0 to towns - 1.roads[i] is [a, b, limit], a road between towns a and b. The limit is a whole number of at least 1. A road may join a town to itself, and two roads may join the same pair.queries[j] is [from, to], two different towns.from to to, or -1 when there is no route.Input: towns = 6, roads = [[0,1,8],[1,2,5],[0,2,3],[2,3,9],[3,4,2],[1,4,4]], queries = [[0,3],[0,4],[0,5],[2,4]]
Output: [5, 4, -1, 4]The solution reads the roads from the highest limit down. Each group keeps a list of the queries that have an end in it. A road that joins two groups answers every waiting query whose two ends it brings together.
| Road read | Groups joined | Queries answered |
|---|---|---|
[2,3,9] |
2 and 3 |
none |
[0,1,8] |
0 and 1 |
none |
[1,2,5] |
0, 1 and 2, 3 |
query 0, from 0 to 3: 5 |
[1,4,4] |
0, 1, 2, 3 and 4 |
query 1, from 0 to 4: 4, and query 3, from 2 to 4: 4 |
Town 5 has no road, so the query from 0 to 5 stays at -1. The remaining roads join groups that are already together.
Input: towns = 2, roads = [[0,1,7]], queries = [[0,1],[1,0]]
Output: [7, 7]A road works in both directions.
Input: towns = 3, roads = [], queries = [[0,2]]
Output: [-1]With no road, no route exists.
1 ≤ towns ≤ 100,0000 ≤ len(roads) ≤ 100,000, and every road is [a, b, limit] with 0 ≤ a, b < towns and 1 ≤ limit ≤ 1,000,0001 ≤ len(queries) ≤ 100,000, and every query joins two different townsAnswering one query by trying the limits and searching the network costs about 100,000 × 100,000 steps. For 100,000 queries that is far beyond any machine. The roads and queries are all known in advance, so you can answer them together in one pass.