package com.u5bf.java;
import java.util.Arrays;
public class DisjointSets {
private int[] set;
private int size;
public DisjointSets(int length) {
this.set = new int[length];
Arrays.fill(this.set, -1);
this.size = length;
}
public int find(int x) {
int root = x;
while (set[root] >= 0) {
root = set[root];
}
// 压缩路径
while (x != root) {
int t = set[x];
set[x] = root;
x = t;
}
return x;
}
public boolean union(int x, int y) {
int xRoot = find(x);
int yRoot = find(y);
if (xRoot == yRoot) {
return false; // 属于同一个集合直接退出
}
if (set[xRoot] <= set[yRoot]) { // xRoot 节点数更多
set[xRoot] += set[yRoot]; // 累加节点总数
set[yRoot] = xRoot;
} else {
set[yRoot] += set[xRoot];
set[xRoot] = yRoot;
}
this.size--;
return true;
}
public int getSize() {
return this.size;
}
public static void main(String[] args) {
DisjointSets set = new DisjointSets(10);
set.union(1, 2);
set.union(3, 4);
set.union(5, 6);
set.union(7, 8);
set.union(8, 9);
set.union(1, 8);
set.union(0, 5);
set.union(1, 9);
System.out.println("并查集的个数为:" + set.getSize());
}
}
并查集(压缩路径)
于 2022-05-06 08:28:23 首次发布