Parcel-delivery app~40 min2s · 256 MBtarget O(n + m) time, O(n + m) spacedfs · traversal
A freight network has n hubs joined by two-way routes. Two hubs may share more than one route, and a route never joins a hub to itself.
When a hub closes, every route that touches it stops working. The remaining hubs may then split into several groups, where hubs in one group can still reach each other. Planners want to know, for each hub, how many groups the other hubs form if that hub alone closes.
Write groups_after_closing(n, routes).
n hubs, numbered from 0 to n - 1.routes[i] is [a, b]: a two-way route between hubs a and b. The same pair may appear more than once, and a differs from b.n. Entry v is the number of groups formed by the other n - 1 hubs when hub v closes.Input: n = 8, routes = [[0,1],[1,2],[2,0],[2,3],[3,4],[4,5],[5,3],[5,6]]
Output: [2, 2, 3, 3, 2, 3, 2, 1]Hubs 0, 1 and 2 form a ring, and so do hubs 3, 4 and 5. Route 2-3 joins the rings, and hub 6 hangs off hub 5. Hub 7 has no routes. Without any closure there are two groups: the big one and hub 7.
The solution walks each group depth first. It records for each hub v a visit time tin[v]. It also records low[v], the earliest visit time that the hub's subtree can reach with one extra route. A walk-child c of v is shut off when low[c] >= tin[v].
| Hub | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| tin | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| low | 0 | 0 | 0 | 3 | 3 | 3 | 6 | 7 |
| shut-off children | 1 | 0 | 1 | 1 | 0 | 1 | 0 | 0 |
Hubs 0 and 7 start a walk, so closing them breaks their group into as many pieces as they have shut-off children: 1 and 0. Every other hub also leaves the piece above it, so it adds 1. There are 2 groups, so closing hub 2 leaves 1 other group + 1 above + 1 shut off = 3.
Input: n = 4, routes = [[0,1],[1,2],[2,3],[3,0]]
Output: [1, 1, 1, 1]Closing any hub of a ring leaves the other three hubs in one group.
Input: n = 5, routes = [[0,1],[0,2],[0,3],[0,4]]
Output: [4, 1, 1, 1, 1]Hub 0 is the centre of a star. Closing it leaves four separate hubs.
1 ≤ n ≤ 100,0000 ≤ routes.length ≤ 100,000, and each route is [a, b] with 0 ≤ a, b < n and a ≠ bClosing each hub and counting groups with a search costs n × (n + m), about 2 × 10^10 steps for the largest input. One depth-first walk with visit and low times answers for every hub together, in about 5 × 10^5 steps.