并查集
1 package my_basic.class_5;
2
3 import java.util.HashMap;
4 import java.util.List;
5
6 public class UnionFind {
7 public static class Node{
8 //任意定义
9
10 }
11 //并查集
12 public static class UnionFindSet {
13 private HashMap<Node, Node> fatherMap;
14 private HashMap<Node, Integer> sizeMap;
15
16 public UnionFindSet(List<Node> list) {
17 fatherMap = new HashMap<Node, Node>();
18 sizeMap = new HashMap<Node, Integer>();
19 makeSet(list);
20 }
21 public void makeSet(List<Node> list) {
22 fatherMap.clear();
23 sizeMap.clear();
24 for (Node node : list) {
25 fatherMap.put(node, node); //所有节点的父亲都是指向自己
26 sizeMap.put(node, 1); //所有节点的size都是1
27
28 }
29 }
30
31 //查找代表节点
32 public Node findHead(Node node) {
33 Node father = fatherMap.get(node);
34 if (father != node) {
35 father = findHead(father);
36 }
37 fatherMap.put(node, father); //扁平化 对查找代表节点的优化操作 查找路径上的节点的父亲都直接指向代表节点
38 return father;
39 }
40
41 public boolean isSameSet(Node a,Node b) {
42 return (findHead(a) == findHead(b));
43 }
44 //a所在的集合和b所在的集合 合并
45 public void union(Node a, Node b) {
46 if (a==null || b==null) {
47 return;
48 }
49 Node headA = findHead(a);
50 Node headB = findHead(b);
51 if (headA != headB) {
52 int aSetSize = sizeMap.get(headA);
53 int bSetSize = sizeMap.get(headB);
54 if (aSetSize < bSetSize) {
55 //合并到b集合
56 fatherMap.put(headA, headB);
57 sizeMap.put(headB, aSetSize+bSetSize);
58 }else {
59 fatherMap.put(headB, headA);
60 sizeMap.put(headA, aSetSize+bSetSize);
61 }
62 }
63 }
64
65 }
66
67 public static void main(String[] args) {
68
69 }
70
71 }