package ufs;
import java.util.HashMap;
import java.util.Map;
/**
* 并查集
* @author zdz
*/
public class UFS {
private Map<Integer,Integer> father = new HashMap<>();
/**
* 初始化,元素对应下标值为 -1,代表元素为根,并且集合中元素只有一个 即|-1|
* @param es
*/
private void init(int[] es){
for(int e : es){
father.put(e,-1);
}
}
public void union(int e1,int e2){
int f1 = findRoot(e1);
int f2 = findRoot(e2);
if(f1 == f2) return ;
int count1 = father.get(f1);
int count2 = father.get(f2);
// 让小树并到大树下面,让树更加平衡!
if(count1 < count2){
father.put(f2,f1);
father.put(f1,count1 + count2);
}else {
father.put(f1,f2);
father.put(f2,count1 + count2);
}
}
/**
* 找到编号为 e 的元素根节点下标!
* @param e
* @return
*/
public int findRoot(int e){
if(father.get(e) > 0) {
e = father.get(e);
}
return e;
}
/**
* 返回并查集中集合的个数!
* @return
*/
public int unionSize(){
int size = 0;
for(Map.Entry<Integer,Integer> entry : father.entrySet()){
if(entry.getValue() == -1){
size++;
}
}
return size;
}
}
并查集实现-java
于 2022-03-28 18:58:50 首次发布