Ride-hailing app~25 min2s · 256 MBtarget O(m log m + (n + m) α(n)) time, O(n + m) spaceunion-find
You work on a ride-hailing app. A city has n pickup zones. The app wants drivers to move between any two zones using priority lanes, which can pass through other zones. Some lanes are already built and cost nothing more.
Your team lead asks: "What is the lowest total cost of new lanes so that every zone reaches every other?" The city has up to 100,000 zones and 200,000 possible new lanes. If no choice of lanes can connect all the zones, the answer is -1.
Write extra_lane_cost(n, lanes, built).
n is the number of zones, numbered 0 to n - 1.lanes[i] = [a, b, cost] is a possible new lane between zones a and b, with a cost in units.built[j] = [a, b] is a lane that already exists. It joins a and b for free, and it can be used in both directions.If the built lanes already connect every zone, the answer is 0.
Input: n = 6, lanes = [[0, 1, 4], [1, 2, 2], [0, 2, 5], [2, 3, 7], [3, 4, 1], [4, 5, 3], [3, 5, 6]], built = [[1, 2]]
Output: 15The built lane joins zones 1 and 2. Going through the new lanes from the cheapest:
| Lane | Cost | Joins two different groups? | Total |
|---|---|---|---|
| 3 to 4 | 1 | yes | 1 |
| 1 to 2 | 2 | no: already built | 1 |
| 4 to 5 | 3 | yes | 4 |
| 0 to 1 | 4 | yes | 8 |
| 0 to 2 | 5 | no: 0 and 2 are already joined | 8 |
| 3 to 5 | 6 | no: 3 and 5 are already joined | 8 |
| 2 to 3 | 7 | yes | 15 |
Input: n = 4, lanes = [[0, 1, 3]], built = [[2, 3]]
Output: -1The zones {0, 1} and {2, 3} can never be joined.
Input: n = 3, lanes = [[0, 2, 9]], built = [[0, 1], [1, 2]]
Output: 01 ≤ n ≤ 100,0000 ≤ len(lanes) ≤ 200,000, with 0 ≤ cost ≤ 1,000,000.0 ≤ len(built) ≤ 100,0000 to n - 1. Lanes can repeat, and a lane can join a zone to itself.Looking for the cheapest useful lane by scanning all lanes, again for each lane you add, costs about 100,000 scans of 200,000 lanes. That is 20 billion steps. Sorting the lanes once costs about 3.5 million comparisons. Then each lane needs only one check of whether it joins two different groups.