๐ณ Maximize Target Nodes After Tree Connection
Imagine you have two separate tree networks that you can temporarily connect with a single bridge! Your mission is to find the optimal connection strategy to maximize reachable nodes.
Given two undirected trees:
- Tree 1:
nnodes labeled [0, n-1] with edges defined byedges1 - Tree 2:
mnodes labeled [0, m-1] with edges defined byedges2
Key Concept: Node u is target to node v if the path between them has an even number of edges (including 0 - every node targets itself).
Your Goal: For each node i in Tree 1, determine the maximum number of nodes that can be target to i after optimally connecting one node from Tree 1 to any node in Tree 2.
Important: Each query is independent - you remove the bridge before testing the next node.
Input & Output
Visualization
Time & Space Complexity
For each of n queries, try nรm bridge combinations, each requiring O(n+m) BFS
Space for adjacency lists and BFS queue
Constraints
- 1 โค n, m โค 105
- edges1.length == n - 1
- edges2.length == m - 1
- edges1[i].length == edges2[i].length == 2
- 0 โค ai, bi < n
- 0 โค ui, vi < m
- The input represents valid trees