Maps app~30 min2s · 256 MBtarget O(m log m + m α(n)) time, O(n + m) spaceclassic twin: lc-1135greedy · union-find
A maps app helps a regional council plan a rural road programme. There are towns numbered from 0, and a list of candidate roads, each with a build cost. A road can be used in both directions.
The council wants to serve the towns as service regions. A region is a set of towns that can reach one another by the roads that are built. It wants exactly regions regions, built for the lowest total cost.
Write cheapest_regions(towns, roads, regions).
towns is the number of towns, numbered 0 to towns - 1.roads[i] is [a, b, cost]: a candidate road between towns a and b. A road may join a town to itself.regions regions.-1 when no choice leaves exactly regions regions.Input: towns = 6, roads = [[0,1,4],[1,2,3],[0,2,5],[2,3,8],[3,4,2],[4,5,6],[3,5,7]], regions = 2
Output: 15The solution tries the roads from the cheapest. It builds a road only when its two towns are in different regions, and it stops when two regions remain.
| Road read | Action | Regions | Total cost |
|---|---|---|---|
| start | 6 | 0 | |
[3,4,2] |
build | 5 | 2 |
[1,2,3] |
build | 4 | 5 |
[0,1,4] |
build | 3 | 9 |
[0,2,5] |
skip: already one region | 3 | 9 |
[4,5,6] |
build, then stop | 2 | 15 |
The regions are the towns 0, 1, 2 and the towns 3, 4, 5.
Input: towns = 6, roads = [[0,1,4],[1,2,3],[0,2,5],[2,3,8],[3,4,2],[4,5,6],[3,5,7]], regions = 1
Output: 23With one region wanted, the road [2,3,8] is built as well: 15 + 8 = 23.
Input: towns = 5, roads = [[0,1,2]], regions = 2
Output: -1One road leaves four regions at best, and two regions are wanted.
1 ≤ towns ≤ 100,000 and 1 ≤ regions ≤ towns0 ≤ len(roads) ≤ 200,000, and every road is [a, b, cost] with 0 ≤ a, b < towns and 0 ≤ cost ≤ 1,000,000Trying every subset of roads takes 2 to the power 200,000 steps. Even trying every order of the roads is far too much. The road costs reach 1,000,000 and there can be 100,000 towns, so a total can pass 2,000,000,000 and needs 64 bits.