并查集2
并查集的实现代码及解析:
1 public class UnionFind { 2 public static class Element<V> { 3 public V value; 4 5 public Element(V value) { 6 this.value = value; 7 } 8 } 9 10 public static class UnionFindSet<V> { 11 public HashMap<V,Element<V>> elementMap; 12 public HashMap<Element<V>,Element<V>> fatherMap; 13 public HashMap<Element<V>,Integer> sizeMap; 14 15 public UnionFindSet(List<V> list) { 16 elementMap = new HashMap<>(); 17 fatherMap = new HashMap<>(); 18 sizeMap = new HashMap<>(); 19 for (V value : list) { 20 Element<V> element = new Element<>(value); 21 elementMap.put(value,element); 22 fatherMap.put(element,element); 23 sizeMap.put(element,1); 24 } 25 } 26 27 public Element<V> find(Element<V> element) { 28 Stack<Element<V>> sk = new Stack<>(); 29 while (element != fatherMap.get(element)) { 30 sk.push(element); 31 element = fatherMap.get(element); 32 } 33 //将同一个集合节点的父亲统一 34 while (!sk.empty()) { 35 fatherMap.put(sk.pop(), element); 36 } 37 return element; 38 } 39 40 public boolean isSameSet(V a,V b) { 41 if (elementMap.containsKey(a) && elementMap.containsKey(b)) { 42 return find(elementMap.get(a)) == find(elementMap.get(b)); 43 } 44 return false; 45 } 46 47 public void union(V a,V b) { 48 Element<V> aF = elementMap.get(a); 49 Element<V> bF = elementMap.get(b); 50 51 if (aF != bF) {//不在同一组的情况下才要进行合并操作 52 Element<V> big = sizeMap.get(find(aF)) >= sizeMap.get(find(bF)) ? aF : bF; 53 Element<V> small = big == aF ? bF : aF; 54 fatherMap.put(small, big); 55 sizeMap.put(big, sizeMap.get(small) + sizeMap.get(big)); 56 sizeMap.remove(small); 57 } 58 } 59 } 60 }