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