Approach
Depth-first search
For Maximize the Number of Target Nodes After Connecting Trees II, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 51 lines of C++ from the credited upstream file 3373.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> maxTargetNodes(vector<vector<int>>& edges1,4 vector<vector<int>>& edges2) {5 const int n = edges1.size() + 1;6 const int m = edges2.size() + 1;7 vector<int> ans;8 const vector<vector<int>> graph1 = buildGraph(edges1);9 const vector<vector<int>> graph2 = buildGraph(edges2);10 vector<bool> parity1(n);11 vector<bool> parity2(m); 12 const int even1 = dfs(graph1, 0, -1, parity1, true);13 const int even2 = dfs(graph2, 0, -1, parity2, true);14 const int odd1 = n - even1;15 const int odd2 = m - even2;16 17 for (int i = 0; i < n; ++i) {18 const int tree1 = parity1[i] ? even1 : odd1;19 20 21 const int tree2 = max(even2, odd2);22 ans.push_back(tree1 + tree2);23 }24 25 return ans;26 }27 28 private:29 30 int dfs(const vector<vector<int>>& graph, int u, int prev,31 vector<bool>& parity, bool isEven) {32 int res = isEven ? 1 : 0;33 parity[u] = isEven;34 for (const int v : graph[u])35 if (v != prev)36 res += dfs(graph, v, u, parity, !isEven);37 return res;38 }39 40 vector<vector<int>> buildGraph(const vector<vector<int>>& edges) {41 vector<vector<int>> graph(edges.size() + 1);42 for (const vector<int>& edge : edges) {43 const int u = edge[0];44 const int v = edge[1];45 graph[u].push_back(v);46 graph[v].push_back(u);47 }48 return graph;49 }50};51