Approach
Depth-first search
For Subtree Inversion Sum, 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
- 46 lines of C++ from the credited upstream file 3544.cpp.
- The implementation visibly relies on sequence storage.
- 2 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 long long subtreeInversionSum(vector<vector<int>>& edges, vector<int>& nums,4 int k) {5 const int n = edges.size() + 1;6 vector<int> parent(n, -1);7 vector<vector<int>> graph(n);8 9 for (const vector<int>& edge : edges) {10 const int u = edge[0];11 const int v = edge[1];12 graph[u].push_back(v);13 graph[v].push_back(u);14 }15 16 vector<vector<vector<long>>> mem(17 n, vector<vector<long>>(k + 1, vector<long>(2, -1)));18 return dfs(graph, 0, k,19 false, nums, k, parent, mem);20 }21 22 private:23 24 25 long dfs(const vector<vector<int>>& graph, int u, int stepsSinceInversion,26 bool inverted, const vector<int>& nums, int k, vector<int>& parent,27 vector<vector<vector<long>>>& mem) {28 if (mem[u][stepsSinceInversion][inverted] != -1)29 return mem[u][stepsSinceInversion][inverted];30 long num = inverted ? -nums[u] : nums[u];31 long negNum = -num;32 for (const int v : graph[u]) {33 if (v == parent[u])34 continue;35 parent[v] = u;36 num += dfs(graph, v, min(k, stepsSinceInversion + 1), inverted, nums, k,37 parent, mem);38 if (stepsSinceInversion == k)39 negNum += dfs(graph, v, 1, !inverted, nums, k,40 parent, mem);41 }42 return mem[u][stepsSinceInversion][inverted] =43 (stepsSinceInversion == k) ? max(num, negNum) : num;44 }45};46