Approach
Depth-first search
For Power Grid Maintenance, 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
- 55 lines of C++ from the credited upstream file power-grid-maintenance.cpp.
- The implementation visibly relies on sequence storage.
- 7 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.
123 45class Solution {6public:7 vector<int> processQueries(int c, vector<vector<int>>& connections, vector<vector<int>>& queries) {8 vector<vector<int>> adj(c);9 for (const auto& c : connections) {10 adj[c[0] - 1].emplace_back(c[1] - 1);11 adj[c[1] - 1].emplace_back(c[0] - 1);12 }13 vector<int> lookup(c, -1);14 const auto& iter_dfs = [&](int i) {15 vector<int> stk = {i};16 while (!empty(stk)) {17 const auto u = stk.back(); stk.pop_back();18 if (lookup[u] != -1) {19 continue;20 }21 lookup[u] = i;22 for (const auto& v : adj[u]) {23 stk.emplace_back(v);24 }25 }26 };27 28 for (int i = 0; i < c; ++i) {29 iter_dfs(i);30 }31 vector<vector<int>> groups(c);32 for (int i = c - 1; i >= 0; --i) {33 groups[lookup[i]].emplace_back(i);34 }35 vector<int> result;36 vector<bool> online(c, true);37 for (const auto& q : queries) {38 const auto t = q[0], x = q[1] - 1;39 if (t == 1) {40 if (online[x]) {41 result.emplace_back(x + 1);42 continue;43 }44 while (!empty(groups[lookup[x]]) && !online[groups[lookup[x]].back()]) {45 groups[lookup[x]].pop_back();46 }47 result.emplace_back(!empty(groups[lookup[x]]) ? groups[lookup[x]].back() + 1 : -1);48 } else {49 online[x] = false;50 }51 }52 return result;53 }54};55