0%
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| class UF { private int count; private int[] parent; private int[] size; public UF(int n) { this.count = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return ; if (size[rootP] < size[rootQ]) { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } else { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } this.count--; } public boolean conneted(int p, int q) { int rootP = find(p); int rootQ = find(q); return rootP == rootQ; } public int count() { return this.count; } private int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } }
|
参考
详解:并查集(Union-Find)