Problem Description
Given n branches (nodes) and an array of roads (edges with weights) that initially connect all branches, determine the number of possible sets of branches that can be closed such that the remaining open branches have a pairwise distance of at most maxDistance. Note that if a branch is closed, all its connecting roads are removed. The remaining set may be empty or consist of a single branch (both are valid). There may be multiple roads between the same two nodes.
Key Insights
- n is small (n ≤ 10), meaning that iterating over all 2^n potential "closed branch" subsets is feasible.
- For each subset, the remaining open branches must abide by the condition that every pair is reachable with distance ≤ maxDistance.
- For each configuration, build a graph using only the open branches and use a shortest-path algorithm (e.g., Floyd–Warshall) to compute pairwise distances.
- Special cases: An active set with 0 or 1 node always trivially satisfies the condition.
- Efficiently filtering valid subsets involves iterating through each subset and verifying the property for each pair of active branches.
Space and Time Complexity
Time Complexity: O(2^n * (n^3 + m))
• There are 2^n subsets.
• For each, we potentially process m roads to build the graph and then run Floyd–Warshall in O(n^3), where n ≤ 10.
Space Complexity: O(n^2) per subset for the distance matrix, along with O(m) for storing the roads.
Solution
The solution iterates over every subset of closed branches (using bitmasks). For each subset, the open branches are extracted. If the count of open branches is 0 or 1, the set is valid by definition. Otherwise, a distance matrix is built for the open branches (initializing distances to infinity except for 0 on the diagonal). For every road, if both endpoints are open, update the distance matrix with the road weight (taking the minimum in case of multiple roads). Then, Floyd–Warshall is run on these nodes to compute all-pairs shortest paths. Finally, for every two distinct open branches, if any distance exceeds maxDistance, the subset is invalid. Otherwise, count it as a valid configuration.
Key data structures and techniques:
- Bitmask/Enumeration for subsets of branches.
- A 2D matrix and Floyd–Warshall algorithm for computing shortest paths.