Approach
Breadth-first search
For Maximum Subgraph Score in a Tree, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 44 lines of C++ from the credited upstream file maximum-subgraph-score-in-a-tree.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 6 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 vector<int> maxSubgraphScore(int n, vector<vector<int>>& edges, vector<int>& good) {8 vector<vector<int>> adj(n);9 for (const auto& e : edges) {10 adj[e[0]].emplace_back(e[1]);11 adj[e[1]].emplace_back(e[0]);12 }13 vector<int> parent(n, -1);14 vector<int> q = {0};15 for (int i = 0; i < n; ++i) {16 const auto u = q[i];17 for (const auto& v : adj[u]) {18 if (v == parent[u]) {19 continue;20 }21 parent[v] = u;22 q.emplace_back(v);23 }24 }25 vector<int> dp(n);26 for (int i = 0; i < n; ++i) {27 dp[i] = good[i] ? 1 : -1;28 }29 for (int i = n - 1; i >= 0; --i) {30 if (parent[q[i]] == -1) {31 continue;32 }33 dp[parent[q[i]]] += max(dp[q[i]], 0);34 }35 for (int i = 0; i < n; ++i) {36 if (parent[q[i]] == -1) {37 continue;38 }39 dp[q[i]] += max(dp[parent[q[i]]] - max(dp[q[i]], 0), 0);40 }41 return dp;42 }43};44