- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 68 lines of Java from the credited upstream file 3108.java.
- The implementation visibly relies on sequence storage.
- 3 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 weight = new int[n];6 for (int i = 0; i < n; ++i)7 id[i] = i;8 9 Arrays.fill(weight, (1 << 17) - 1);10 }11 12 public void unionByRank(int u, int v, int w) {13 final int i = find(u);14 final int j = find(v);15 final int newWeight = weight[i] & weight[j] & w;16 weight[i] = newWeight;17 weight[j] = newWeight;18 if (i == j)19 return;20 if (rank[i] < rank[j]) {21 id[i] = j;22 } else if (rank[i] > rank[j]) {23 id[j] = i;24 } else {25 id[i] = j;26 ++rank[j];27 }28 }29 30 public int getMinCost(int u, int v) {31 if (u == v)32 return 0;33 final int i = find(u);34 final int j = find(v);35 return i == j ? weight[i] : -1;36 }37 38 private int[] id;39 private int[] rank;40 private int[] weight;41 42 private int find(int u) {43 return id[u] == u ? u : (id[u] = find(id[u]));44 }45}46 47class Solution {48 public int[] minimumCost(int n, int[][] edges, int[][] query) {49 int[] ans = new int[query.length];50 UnionFind uf = new UnionFind(n);51 52 for (int[] edge : edges) {53 final int u = edge[0];54 final int v = edge[1];55 final int w = edge[2];56 uf.unionByRank(u, v, w);57 }58 59 for (int i = 0; i < query.length; ++i) {60 final int u = query[i][0];61 final int v = query[i][1];62 ans[i] = uf.getMinCost(u, v);63 }64 65 return ans;66 }67}68