You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.5 KiB

2 years ago
package 03.mca_06;
public class Code01_Test2 {
public static class UnionFind {
// father[i] : i号点往上的是几号点
public int[] father;
// size[i] : i号点如果是代表点的话size[i]才有意义,代表集合的大小
public int[] size;
public int[] help;
public UnionFind(int n) {
father = new int[n];
size = new int[n];
help = new int[n];
for (int i = 0; i < n; i++) {
father[i] = i;
size[i] = 1;
}
}
// i号点往上到不能再往上是什么点返回
private int find(int i) {
int size = 0;
while (i != father[i]) {
help[size++] = i;
i = father[i];
}
while (size > 0) {
father[help[--size]] = i;
}
return i;
}
public boolean isSameSet(int x, int y) {
return find(x) == find(y);
}
// x背后的集合彻底和y背后的集合合在一起
public void union(int x, int y) {
int fx = find(x);
int fy = find(y);
if (fx != fy) {
int sizeX = size[fx];
int sizeY = size[fy];
if (sizeX >= sizeY) {
father[fy] = fx;
size[fx] += size[fy];
} else {
father[fx] = fy;
size[fy] += size[fx];
}
}
}
}
public static void main(String[] args) {
int n = 100;
UnionFind uf = new UnionFind(n);
System.out.println(uf.isSameSet(4, 60));
// 4 0 90
// 60 80 30
uf.union(4, 0);
uf.union(60, 80);
uf.union(0, 90);
uf.union(80, 30);
uf.union(90, 30);
System.out.println(uf.isSameSet(4, 60));
}
}