Parcel-delivery app~30 min2s · 256 MBtarget O((n + m) × α(n)) time, O(n + m) spaceunion-find
You work on a freight network. There are n depots, numbered 0 to n - 1, joined by two-way roads. During a flood, some roads close one at a time, in a known order.
Two depots are in the same region when trucks can drive from one to the other over the roads that are still open. A depot with no open road is a region of its own.
Your team lead asks: "After each closure, how many separate regions does the network have?" The network can have 100,000 depots and 100,000 roads.
Write regions_after_closures(n, roads, closures).
roads[i] = [a, b] is a two-way road between depots a and b. Roads can repeat, and a can equal b.closures lists road numbers in the order the roads close. A road number appears at most once. A road that is not listed never closes.k is the number of regions after the first k + 1 closures, with every other road still open.Input: n = 5, roads = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 4]], closures = [0, 2, 4, 1]
Output: [1, 2, 3, 4]The five depots form a ring. The roads are numbered 0 to 4 in the order given. After each closure:
| Closures so far | Closed road | Roads still open | Regions |
|---|---|---|---|
| 1 | road 0 | (1, 2), (2, 3), (3, 4), (0, 4) | 1 |
| 2 | road 2 | (1, 2), (3, 4), (0, 4) | 2 |
| 3 | road 4 | (1, 2), (3, 4) | 3 |
| 4 | road 1 | (3, 4) | 4 |
The ring stays in one piece after one closure. After the second closure it splits.
Input: n = 3, roads = [[0, 1], [0, 1]], closures = [0]
Output: [2]The second road still joins depots 0 and 1, so the regions are {0, 1} and {2}.
Input: n = 4, roads = [[0, 1], [2, 3]], closures = [1, 0]
Output: [3, 4]Closing road 1 separates depots 2 and 3. Closing road 0 then separates depots 0 and 1.
1 ≤ n ≤ 100,0000 ≤ len(roads) ≤ 100,0000 ≤ roads[i][0], roads[i][1] < n0 ≤ len(closures) ≤ len(roads), and each road number appears at most onceSearching the whole network again after every closure costs about 200,000 steps for each of 100,000 closures, which is 20 billion steps. Union-find can only merge regions, never split them. So it needs the closures to be turned into openings.