1.union
2.查
//节点定义
public static class Node {
// whatever you like
}
//主要类
public static class DisjointSets {
//(key,value)表示,key的父节点,是value,(Data_A,Data_B)代表,Data_A的父节点是Data_B
public HashMap<Node, Node> fatherMap;
//Node为代表节点,Integer为元素的个数,若Node不为代表节点,Integer为无用
public HashMap<Node, Integer> rankMap ;
public DisjointSets() {
fatherMap = new HashMap<Node, Node>();
rankMap = new HashMap<Node, Integer>();
}
public void makeSets(List<Node> nodes) {
fatherMap.clear();
rankMap.clear();
for (Node node : nodes) {
fatherMap.put(node, node);
rankMap.put(node, 1);
}
}
//找代表的过程
public Node findFather(Node n) {
Node father = fatherMap.get(n);
if (father != n) {
father = findFather(father);
}
fatherMap.put(n, father);
return father;
}
//是否属于同一个集合
public boolean isSameSet(Node a,Node b){
return findFather(a) == findFather(b);
}
public void union(Node a, Node b) {
if (a == null || b == null) {
return;
}
Node aFather = findFather(a);
Node bFather = findFather(b);
if (aFather != bFather) {
int aFrank = rankMap.get(aFather);
int bFrank = rankMap.get(bFather);
if (aFrank <= bFrank) {
fatherMap.put(aFather, bFather);
rankMap.put(bFather, aFrank + bFrank);
} else {
fatherMap.put(bFather, aFather);
rankMap.put(aFather, aFrank + bFrank);
}
}
}
}