Approach
Depth-first search
For Choose Edges to Maximize Score in a Tree, 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
- 34 lines of C++ from the credited upstream file 2378.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 maxScore(vector<vector<int>>& edges) {4 const int n = edges.size();5 vector<vector<pair<int, int>>> graph(n);6 7 for (int i = 0; i < n; ++i) {8 const int parent = edges[i][0];9 const int weight = edges[i][1];10 if (parent != -1)11 graph[parent].emplace_back(i, weight);12 }13 14 const auto [takeRoot, notTakeRoot] = dfs(graph, 0);15 return max(takeRoot, notTakeRoot);16 }17 18 private:19 20 21 pair<long, long> dfs(const vector<vector<pair<int, int>>>& graph, int u) {22 long bestEdge = 0;23 long notTakeU = 0;24 25 for (const auto& [v, w] : graph[u]) {26 const auto [takeV, notTakeV] = dfs(graph, v);27 bestEdge = max(bestEdge, w + notTakeV - takeV);28 notTakeU += takeV;29 }30 31 return {bestEdge + notTakeU, notTakeU};32 }33};34