[LeetCode] Power Grid Maintenance

3607. Power Grid Maintenance

You are given an integer c representing c power stations, each with a unique identifier id from 1 to c (1‑based indexing).

These stations are interconnected via n bidirectional cables, represented by a 2D array connections, where each element connections[i] = [ui, vi] indicates a connection between station ui and station vi. Stations that are directly or indirectly connected form a power grid.

Initially, all stations are online (operational).

You are also given a 2D array queries, where each query is one of the following two types:

  • [1, x]: A maintenance check is requested for station x. If station x is online, it resolves the check by itself. If station x is offline, the check is resolved by the operational station with the smallest id in the same power grid as x. If no operational station exists in that grid, return -1.
  • [2, x]: Station x goes offline (i.e., it becomes non-operational).

Return an array of integers representing the results of each query of type [1, x] in the order they appear.

Note: The power grid preserves its structure; an offline (non‑operational) node remains part of its grid and taking it offline does not alter connectivity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
int vis[101010];
bool online[101010];
class Solution {
vector<vector<int>> adj;
void dfs(int u, int root) {
vis[u] = root;
for(auto& v : adj[u]) {
if(!vis[v]) dfs(v,root);
}
}
public:
vector<int> processQueries(int c, vector<vector<int>>& connections, vector<vector<int>>& queries) {
memset(vis, 0, sizeof vis);
adj = vector<vector<int>>(c + 1);
for(auto& c : connections) {
int u = c[0], v = c[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
for(int i = 1; i <= c; i++) if(!vis[i]) dfs(i,i);
unordered_map<int,deque<int>> groups;
for(int i = 1; i <= c; i++) {
groups[vis[i]].push_back(i);
online[i] = 1;
}
vector<int> res;
for(auto& q : queries) {
int op = q[0], u = q[1];
if(op == 1) {
if(online[u]) res.push_back(u);
else {
int g = vis[u];
while(groups[g].size() and !online[groups[g][0]]) groups[g].pop_front();
res.push_back(groups[g].size() ? groups[g][0] : -1);
}
}
if(op == 2) online[u] = 0;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/07/08/PS/LeetCode/power-grid-maintenance/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.