Problem Description
Given two undirected trees – one with n nodes (labeled 0 to n - 1) and another with m nodes (labeled 0 to m - 1) – and an integer k, each tree is provided as an edge list. For any two nodes u and v (which may be in different trees after an added connecting edge) we call v “target” to u if the number of edges on the path from u to v is less than or equal to k. For every node i in the first tree, you are allowed to add one extra edge connecting any node in the first tree and any node in the second tree (queries are independent). The goal is to maximize the total number of nodes that become target to node i, counting those in the first tree (using tree1’s intrinsic connectivity) as well as the nodes in the second tree (reached via the added connecting edge) and return an answer array of length n.
Key Insights
- In tree1, for any node i, one may precompute the number of nodes reachable within k edges (by a simple BFS per node).
- The added connecting edge always “costs” 1 edge. When connecting node i (or some other node u in tree1) to a node v in tree2, the remaining “budget” to travel inside tree2 is k - (distance from i to u + 1).
- Because trees have the property that distance(i, i) is 0, the optimal solution is always achieved by choosing u = i. This gives the maximum remaining budget for tree2 nodes, which is (k - 1).
- Precompute for tree2, for every node, the number of nodes reachable within a radius of (k - 1) (if k ≥ 1). Then, take the maximum among these counts (denoted as best2). In case k is 0, no connection is allowed so only tree1’s reachable nodes are counted.
- Thus, for each node i in tree1, the answer is: • tree1_reachable_count(i, k) + (if k ≥ 1 then best2 else 0).
Space and Time Complexity
Time Complexity: O(n^2 + m^2) in the worst-case, due to performing BFS from every node in tree1 and tree2. Space Complexity: O(n + m) for storing the graphs and the BFS queue at any given time.
Solution
We start by building the adjacency lists for both trees based on the given edge arrays. For each node in tree1, run a BFS to count how many nodes are at a distance ≤ k (this gives the tree1 contribution per node).
For tree2, since the connecting edge uses up 1 step, we are interested in the maximum number of nodes reachable with a remaining budget of (k-1). Run a BFS from every node in tree2 (if k ≥ 1) to compute the reachable count, and maintain the maximum value among all nodes (best2).
Since the optimal connection on tree1 is achieved by choosing the same node i (giving a cost of 0 before the connection), every answer for node i is simply the sum of: • The count of tree1 nodes reachable within k from i. • best2 (the optimal tree2 reachable count with radius k-1) if k ≥ 1; otherwise 0.
This greedy observation avoids iterating over all potential connecting nodes in tree1, and simplifies the solution considerably.