Problem Description
Given n cities (numbered from 1 to n) connected by n-1 edges forming a tree, count, for every d from 1 to n-1, the number of subtrees (i.e. connected subsets of nodes) whose maximum distance (measured as number of edges in the unique path between two cities) is exactly d.
Key Insights
- Since n is at most 15, it is feasible to enumerate every subset (using bitmasking) in O(2^n) time.
- For each subset, first check connectivity (using DFS or BFS over nodes in the subset).
- For connected subsets with at least two nodes, compute the tree’s diameter (the maximum distance between any two nodes). This can be done via:
- Running two BFS/DFS traversals (first to find an extreme node, then to measure the distance from that extreme).
- Or performing a pairwise check (acceptable since n is small).
- Increment the count for the corresponding maximum distance if it falls in the range [1, n-1].
Space and Time Complexity
Time Complexity: O(2^n * (n + n)), roughly O(2^n * n) where n is up to 15. Space Complexity: O(n + 2^n) due to the recursion/queue space and storing the graph (though the dominant factor is the enumeration loop over bitmasks).
Solution
We solve the problem by enumerating each possible subset of nodes using bitmasking. For each subset that contains at least two cities, we perform the following steps:
- Check connectivity by selecting an arbitrary node in the subset and using DFS to see if all nodes in the subset can be reached.
- If the subset is connected, compute the diameter of the subtree. One efficient approach is:
- Pick any node in the subset and perform BFS to find the farthest node from it.
- Then perform BFS starting from that farthest node to compute the maximum distance (the diameter).
- Use the computed diameter to update the answer count for that specific distance. This use of bitmask enumeration and exploiting tree properties allows solving the problem within the small constraint of n ≤ 15.