- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 94 lines of C++ from the credited upstream file 1489.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks 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) : id(n), rank(n) {4 iota(id.begin(), id.end(), 0);5 }6 7 void unionByRank(int u, int v) {8 const int i = find(u);9 const int j = find(v);10 if (i == j)11 return;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 }21 22 int find(int u) {23 return id[u] == u ? u : id[u] = find(id[u]);24 }25 26 private:27 vector<int> id;28 vector<int> rank;29};30 31class Solution {32 public:33 vector<vector<int>> findCriticalAndPseudoCriticalEdges(34 int n, vector<vector<int>>& edges) {35 vector<int> criticalEdges;36 vector<int> pseudoCriticalEdges;37 38 39 for (int i = 0; i < edges.size(); ++i)40 edges[i].push_back(i);41 42 43 ranges::sort(edges, ranges::less{},44 [](const vector<int>& edge) { return edge[2]; });45 46 const int mstWeight = getMSTWeight(n, edges, {}, -1);47 48 for (const vector<int>& edge : edges) {49 const int index = edge[3];50 51 52 if (getMSTWeight(n, edges, {}, index) > mstWeight)53 criticalEdges.push_back(index);54 55 else if (getMSTWeight(n, edges, edge, -1) == mstWeight)56 pseudoCriticalEdges.push_back(index);57 }58 59 return {criticalEdges, pseudoCriticalEdges};60 }61 62 private:63 int getMSTWeight(int n, const vector<vector<int>>& edges,64 const vector<int>& firstEdge, int deletedEdgeIndex) {65 int mstWeight = 0;66 UnionFind uf(n);67 68 if (!firstEdge.empty()) {69 uf.unionByRank(firstEdge[0], firstEdge[1]);70 mstWeight += firstEdge[2];71 }72 73 for (const vector<int>& edge : edges) {74 const int u = edge[0];75 const int v = edge[1];76 const int weight = edge[2];77 const int index = edge[3];78 if (index == deletedEdgeIndex)79 continue;80 if (uf.find(u) == uf.find(v))81 continue;82 uf.unionByRank(u, v);83 mstWeight += weight;84 }85 86 const int root = uf.find(0);87 for (int i = 0; i < n; ++i)88 if (uf.find(i) != root)89 return INT_MAX;90 91 return mstWeight;92 }93};94