Number of Possible Sets of Closing Branches - Problem
A company has n branches connected by roads across the country. Due to excessive travel time between branches, they want to close some branches to optimize operations.
The key constraint: all remaining branches must be within maxDistance of each other. When a branch closes, all roads connected to it become inaccessible.
Goal: Count how many different valid sets of branches can remain open (including keeping all branches open if possible).
Input:
n: number of branchesmaxDistance: maximum allowed distance between any two remaining branchesroads: array of[u, v, weight]representing roads between branches
Output: Number of possible valid sets of remaining branches.
Input & Output
example_1.py โ Simple Triangle
$
Input:
n = 3, maxDistance = 12, roads = [[0,1,2],[1,2,10],[0,2,10]]
โบ
Output:
5
๐ก Note:
Valid subsets: {} (empty), {0}, {1}, {2}, {0,1}. The subset {0,2} has distance 10 โค 12, {1,2} has distance 10 โค 12, and {0,1,2} has max distance 10 โค 12, so total is 8 valid subsets.
example_2.py โ Linear Chain
$
Input:
n = 3, maxDistance = 5, roads = [[0,1,2],[1,2,10]]
โบ
Output:
5
๐ก Note:
Valid subsets: {}, {0}, {1}, {2}, {0,1}. Subsets {0,2}, {1,2}, {0,1,2} are invalid because distance between 0 and 2 is 12 > 5.
example_3.py โ Single Node
$
Input:
n = 1, maxDistance = 10, roads = []
โบ
Output:
2
๐ก Note:
Valid subsets: {} (empty set) and {0} (single branch). Both satisfy the constraint trivially.
Visualization
Tap to expand
Understanding the Visualization
1
Enumerate Possibilities
Consider all 2^n ways to close branches using bitmasks
2
Extract Subgraph
For each subset, build the network of remaining branches
3
Compute Distances
Use Floyd-Warshall to find shortest paths between all remaining branches
4
Validate Constraint
Check if maximum distance โค maxDistance requirement is satisfied
Key Takeaway
๐ฏ Key Insight: This is a classic enumeration problem where we must check all possible combinations. The exponential time is unavoidable, but the constraint n โค 15 makes it computationally feasible.
Time & Space Complexity
Time Complexity
O(2^n ร n^3)
2^n subsets, each requiring O(n^3) Floyd-Warshall computation
โ Quadratic Growth
Space Complexity
O(n^2)
Distance matrix for Floyd-Warshall algorithm
โ Quadratic Space
Constraints
- 1 โค n โค 15
- 1 โค maxDistance โค 105
- 0 โค roads.length โค n ร (n-1) / 2
- roads[i].length == 3
- 0 โค ui, vi โค n-1
- ui โ vi
- 1 โค wi โค 105
- At most one road between any pair of branches
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code