Skip to content

Commit 7609d88

Browse files
authored
Create 3607. Power Grid Maintenance (#928)
2 parents 256f5ee + d62528c commit 7609d88

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

3607. Power Grid Maintenance

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution {
2+
public:
3+
struct DSU {
4+
vector<int> p, sz;
5+
DSU(int n=0): p(n+1), sz(n+1,1){
6+
iota(p.begin(), p.end(), 0);
7+
}
8+
int find(int x){ return p[x]==x? x : p[x]=find(p[x]); }
9+
void unite(int a, int b){
10+
a = find(a); b = find(b);
11+
if(a==b) return;
12+
if(sz[a] < sz[b]) swap(a,b);
13+
p[b]=a; sz[a]+=sz[b];
14+
}
15+
};
16+
17+
vector<int> processQueries(int c, vector<vector<int>>& connections, vector<vector<int>>& queries) {
18+
DSU dsu(c);
19+
for (auto &e : connections) dsu.unite(e[0], e[1]);
20+
21+
unordered_map<int, priority_queue<int, vector<int>, greater<int>>> heap;
22+
heap.reserve(c*2);
23+
24+
for (int i = 1; i <= c; ++i) {
25+
int r = dsu.find(i);
26+
heap[r].push(i);
27+
}
28+
29+
vector<char> offline(c+1, false);
30+
vector<int> ans;
31+
ans.reserve(queries.size());
32+
33+
for (auto &q : queries) {
34+
int t = q[0], x = q[1];
35+
if (t == 2) {
36+
offline[x] = true;
37+
} else {
38+
if (!offline[x]) {
39+
ans.push_back(x);
40+
} else {
41+
int r = dsu.find(x);
42+
auto &pq = heap[r];
43+
while (!pq.empty() && offline[pq.top()]) pq.pop();
44+
if (pq.empty()) ans.push_back(-1);
45+
else ans.push_back(pq.top());
46+
}
47+
}
48+
}
49+
return ans;
50+
}
51+
};

0 commit comments

Comments
 (0)