- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 77 lines of C++ from the credited upstream file 1579.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class UnionFind {2 public:3 UnionFind(int n) : count(n), id(n), rank(n) {4 iota(id.begin(), id.end(), 0);5 }6 7 bool unionByRank(int u, int v) {8 const int i = find(u);9 const int j = find(v);10 if (i == j)11 return false;12 if (rank[i] < rank[j]) {13 id[i] = j;14 } else if (rank[i] > rank[j]) {15 id[j] = i;16 } else {17 id[i] = j;18 ++rank[j];19 }20 --count;21 return true;22 }23 24 int getCount() const {25 return count;26 }27 28 private:29 int count;30 vector<int> id;31 vector<int> rank;32 33 int find(int u) {34 return id[u] == u ? u : id[u] = find(id[u]);35 }36};37 38class Solution {39 public:40 int maxNumEdgesToRemove(int n, vector<vector<int>>& edges) {41 UnionFind alice(n);42 UnionFind bob(n);43 int requiredEdges = 0;44 45 46 ranges::sort(edges, ranges::greater{},47 [](const vector<int>& edge) { return edge[0]; });48 49 for (const vector<int>& edge : edges) {50 const int type = edge[0];51 const int u = edge[1] - 1;52 const int v = edge[2] - 1;53 switch (type) {54 case 3: 55 56 57 58 if (alice.unionByRank(u, v) | bob.unionByRank(u, v))59 ++requiredEdges;60 break;61 case 2: 62 if (bob.unionByRank(u, v))63 ++requiredEdges;64 break;65 case 1: 66 if (alice.unionByRank(u, v))67 ++requiredEdges;68 break;69 }70 }71 72 return alice.getCount() == 1 && bob.getCount() == 173 ? edges.size() - requiredEdges74 : -1;75 }76};77