Parcel-delivery app~25 min2s · 256 MBtarget O((hubs + belts) α(hubs)) time, O(hubs) spaceclassic twin: lc-1319union-find
A parcel-delivery app runs sorting hubs numbered from 0. Conveyor belts join pairs of hubs, and a parcel can travel along any belt in either direction. A piece is a set of hubs that parcels can reach from one another.
A belt is redundant when its hubs stay in one piece without it. A technician can move a redundant belt to join two different pieces, or fit one spare belt from the store room. Each of these is one job.
Write rewires_needed(hubs, belts, spares).
hubs is the number of hubs, numbered 0 to hubs - 1.belts[i] is [a, b], a belt between hubs a and b. A belt may join a hub to itself, and two belts may join the same pair.spares is the number of spare belts in the store room.-1 when no jobs can do it.Input: hubs = 6, belts = [[0,1],[0,2],[0,3],[1,2],[1,3]], spares = 0
Output: 2The solution gives every hub its own group, then reads the belts. A belt between two groups joins them. A belt inside one group is redundant, and counts as free.
| Belt read | Pieces left | Free belts |
|---|---|---|
| start | 6 | 0 |
[0,1] |
5 | 0 |
[0,2] |
4 | 0 |
[0,3] |
3 | 0 |
[1,2] |
3 | 1 |
[1,3] |
3 | 2 |
Three pieces need two jobs, and two free belts are ready, so the answer is 2.
Input: hubs = 4, belts = [[0,1],[1,2]], spares = 0
Output: -1Two pieces need one job, but every belt is needed where it is and there is no spare.
Input: hubs = 4, belts = [[0,1],[1,2]], spares = 1
Output: 1The spare belt joins hub 3 to the others.
1 ≤ hubs ≤ 100,0000 ≤ len(belts) ≤ 100,000, and every hub number is from 0 to hubs - 10 ≤ spares ≤ 100,000Testing each belt by flooding the network costs about 100,000 × 100,000 steps for one job, and there can be thousands of jobs. Each belt needs a near-constant check, so you need groups that merge.