- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 74 lines of Java from the credited upstream file 1579.java.
- The implementation visibly relies on sequence storage.
- 2 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 count = n;4 id = new int[n];5 rank = new int[n];6 for (int i = 0; i < n; ++i)7 id[i] = i;8 }9 10 public boolean unionByRank(int u, int v) {11 final int i = find(u);12 final int j = find(v);13 if (i == j)14 return false;15 if (rank[i] < rank[j]) {16 id[i] = j;17 } else if (rank[i] > rank[j]) {18 id[j] = i;19 } else {20 id[i] = j;21 ++rank[j];22 }23 --count;24 return true;25 }26 27 public int getCount() {28 return count;29 }30 31 private int count;32 private int[] id;33 private int[] rank;34 35 private int find(int u) {36 return id[u] == u ? u : (id[u] = find(id[u]));37 }38}39 40class Solution {41 public int maxNumEdgesToRemove(int n, int[][] edges) {42 UnionFind alice = new UnionFind(n);43 UnionFind bob = new UnionFind(n);44 int requiredEdges = 0;45 46 47 Arrays.sort(edges, Comparator.comparingInt(edge -> - edge[0]));48 49 for (int[] edge : edges) {50 final int type = edge[0];51 final int u = edge[1] - 1;52 final 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 }69 }70 71 return alice.getCount() == 1 && bob.getCount() == 1 ? edges.length - requiredEdges : -1;72 }73}74