publicclassUnionSet{ publicstaticvoidmain(String[] args){ Data[] datas = new Data[5]; List<Data> list = new LinkedList<Data>(); for (int i = 0; i < 5; i++) { datas[i] = new Data(); list.add(datas[i]); } UnionFindSet unionFindSet = new UnionFindSet(list); unionFindSet.union(datas[1],datas[2]); System.out.println(unionFindSet.isSameSet(datas[1],datas[2])); }
publicstaticclassData{
}
publicstaticclassUnionFindSet{ //(key,value)表示,key的父节点,是value,(Data_A,Data_B)代表,Data_A的父节点是Data_B public HashMap<Data, Data> fatherMap; public HashMap<Data, Integer> sizeMap;
publicUnionFindSet(List<Data> nodes){ fatherMap = new HashMap<Data, Data>(); sizeMap = new HashMap<Data, Integer>(); makeSets(nodes); }
private Data findHead(Data node){ Data father = fatherMap.get(node); if (father != node) father = findHead(father); fatherMap.put(node, father); return father; }
publicbooleanisSameSet(Data a, Data b){ return findHead(a) == findHead(b); }
publicvoidunion(Data a, Data b){ if (a == null || b == null) return; Data aHead = findHead(a); Data bHead = findHead(b); if (aHead != bHead) { int aSetSize = sizeMap.get(aHead); int bSetSize = sizeMap.get(bHead); if (aSetSize <= bSetSize) { fatherMap.put(aHead, bHead); sizeMap.put(bHead, aSetSize + bSetSize); } else { fatherMap.put(bHead, aHead); sizeMap.put(aHead, aSetSize + bSetSize); } } } } }