class UnionFind {
int n; // 并查集大小
int[] father; // 父亲数组,father[i]的值为:节点i的父亲节点
int[] size; // 集合的大小,size[i]的值为:节点i所在集合的大小
// 构造函数,输入n为并查集大小
public UnionFind(int n) {
this.n = n;
this.father = new int[n];
this.size = new int[n];
for (int i = 0; i < n; i++) {
this.father[i] = i; // 初始的时候,节点i的父亲节点就是自己
this.size[i] = 1; // 初始的时候,每个集合的大小都是1
}
}
// 查找函数,查找节点i的父亲节点(集合的代表节点)
public int find(int i) {
if (i == father[i]) {
return i;
} else {
father[i] = find(father[i]);
return father[i];
}
}
// 合并函数,合并节点i和节点j
public void union(int i, int j) {
int father_i = find(i);
int father_j = find(j);
if (father_i == father_j) return; // 如果俩个元素是一个集合,不需要合并,直接返回
if (size[father_i] <= size[father_j]) {
size[father_j] += size[father_i];
father[father_i] = father_j;
} else {
size[father_i] += size[father_j];
father[father_j] = father_i;
}
}
}
并查集模板
于 2024-07-15 14:22:39 首次发布