diff --git a/3607. Power Grid Maintenance b/3607. Power Grid Maintenance new file mode 100644 index 0000000..c9b67ff --- /dev/null +++ b/3607. Power Grid Maintenance @@ -0,0 +1,51 @@ +class Solution { +public: + struct DSU { + vector p, sz; + DSU(int n=0): p(n+1), sz(n+1,1){ + iota(p.begin(), p.end(), 0); + } + int find(int x){ return p[x]==x? x : p[x]=find(p[x]); } + void unite(int a, int b){ + a = find(a); b = find(b); + if(a==b) return; + if(sz[a] < sz[b]) swap(a,b); + p[b]=a; sz[a]+=sz[b]; + } + }; + + vector processQueries(int c, vector>& connections, vector>& queries) { + DSU dsu(c); + for (auto &e : connections) dsu.unite(e[0], e[1]); + + unordered_map, greater>> heap; + heap.reserve(c*2); + + for (int i = 1; i <= c; ++i) { + int r = dsu.find(i); + heap[r].push(i); + } + + vector offline(c+1, false); + vector ans; + ans.reserve(queries.size()); + + for (auto &q : queries) { + int t = q[0], x = q[1]; + if (t == 2) { + offline[x] = true; + } else { + if (!offline[x]) { + ans.push_back(x); + } else { + int r = dsu.find(x); + auto &pq = heap[r]; + while (!pq.empty() && offline[pq.top()]) pq.pop(); + if (pq.empty()) ans.push_back(-1); + else ans.push_back(pq.top()); + } + } + } + return ans; + } +};