-
Notifications
You must be signed in to change notification settings - Fork 0
/
DisjointSet.java
97 lines (73 loc) · 2.35 KB
/
DisjointSet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package by.bsu.mmf.datastructure.set;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class DisjointSet {
private Map<Integer, Node> nodesMap = new HashMap<>();
public void makeSet(int value) {
Node node = new Node(value);
nodesMap.put(value, node);
}
public void union(int a, int b) {
Node representativeNodeForA = findRepresentativeNode(a);
Node representativeNodeForB = findRepresentativeNode(b);
if(representativeNodeForA.equals(representativeNodeForB)) {
} else if(representativeNodeForA.getRank() > representativeNodeForB.getRank()) {
representativeNodeForB.setParent(representativeNodeForA);
} else if(representativeNodeForA.getRank() == representativeNodeForB.getRank()) {
representativeNodeForB.setParent(representativeNodeForA);
representativeNodeForA.incrementRank();
} else if(representativeNodeForA.getRank() < representativeNodeForB.getRank()) {
representativeNodeForA.setParent(representativeNodeForB);
}
}
public Node findRepresentativeNode(int value) {
Node representativeNode = nodesMap.get(value);
while (representativeNode.getParent() != null) {
representativeNode = representativeNode.getParent();
}
return representativeNode;
}
}
class Node {
private int value;
private int rank;
private Node parent;
public Node(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public int getRank() {
return rank;
}
public void incrementRank() {
rank++;
}
public void setRank(int rank) {
this.rank = rank;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return value == node.value &&
rank == node.rank &&
Objects.equals(parent, node.parent);
}
@Override
public int hashCode() {
return Objects.hash(value, rank, parent);
}
}