public class UnionTree {
private int[] parent;
private int[] size;//记录树的大小
private int total;
private int groups;
public void init(int n){
assert(n>0);
parent = new int[n];
for(int i=0; i<n; i++){
parent[i] = i;
}
size = new int[n];
for(int i=0; i<n; i++){
size[i] = 1;
}
total = n;
groups = n;
}
public int find(int p){
assert(p>=0 && p<total);
int v = parent[p];
while(v != p){
p = v;
v = parent[p];
}
parent[p] = v;//路径压缩
return v;
}
public boolean isConnected(int p1, int p2){
assert(p1 != p2);
assert(p1>=0 && p1<total);
assert(p2>=0 && p2<total);
int v1 = find(p1);
int v2 = find(p2);
return v1==v2 ? true : false;
}
public void union(int p1, int p2){
int v1 = find(p1);
int v2 = find(p2);
if(v1 == v2){
return;
}
//size小的树作为子树和size大的树进行合并,尽量的保持整棵树的平衡
if(size[v1] < size[v2]){
parent[v1] = v2;
}else{
if(size[v1] == size[v2]){
size[v1]++;
}
parent[v2] = v1;
}
groups--;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
并查集之树状数组
最新推荐文章于 2023-08-12 15:56:25 发布