- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 54 lines of Java from the credited upstream file 1724.java.
- The implementation visibly relies on sequence storage, ordered lookup.
- 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 id = new TreeMap[n];4 for (int i = 0; i < n; ++i) {5 id[i] = new TreeMap<>();6 id[i].put(0, i);7 }8 }9 10 public void union(int u, int v, int limit) {11 final int i = find(u, limit);12 final int j = find(v, limit);13 if (i == j)14 return;15 id[i].put(limit, j);16 }17 18 public int find(int u, int limit) {19 20 final int floorKey = id[u].floorKey(limit);21 final int i = id[u].get(floorKey);22 if (i == u)23 return u;24 25 final int j = find(i, limit);26 id[u].put(limit, j);27 return j;28 }29 30 31 private TreeMap<Integer, Integer>[] id;32}33 34class DistanceLimitedPathsExist {35 public DistanceLimitedPathsExist(int n, int[][] edgeList) {36 uf = new UnionFind(n);37 38 Arrays.sort(edgeList, Comparator.comparingInt(edge -> edge[2]));39 40 for (int[] edge : edgeList) {41 final int u = edge[0];42 final int v = edge[1];43 final int d = edge[2];44 uf.union(u, v, d);45 }46 }47 48 public boolean query(int p, int q, int limit) {49 return uf.find(p, limit - 1) == uf.find(q, limit - 1);50 }51 52 private UnionFind uf;53}54