-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunion_find.py
80 lines (65 loc) · 1.93 KB
/
union_find.py
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
class Set:
"""
Union-Find Data Structure.
Heuristics: path compression, union by rank.
"""
def __init__(self, value):
"""
Generate a set containing value.
"""
self.value = value
self.parent = self
self.next = self
self.rank = 0
def findSet(self):
"""
Returns the representative element of
the set and applies path-compression.
"""
pathToRoot = []
element = self
while element is not element.parent:
pathToRoot.append(element)
element = element.parent
root = element
for element in pathToRoot:
element.parent = root
return root
def union(self, other):
"""
Merges two sets applying union by rank.
"""
selfRep = self.findSet()
otherRep = other.findSet()
if selfRep is not otherRep:
if selfRep.rank < otherRep.rank:
selfRep.parent = otherRep.parent
else:
otherRep.parent = selfRep.parent
if selfRep.rank == otherRep.rank:
selfRep.rank += 1
selfRep.next, otherRep.next = otherRep.next, selfRep.next
def add(self, value):
"""
Inserts value into the set.
"""
self.union(Set(value))
def getElements(self):
"""
Generator for the elements in the set.
"""
yield self.value
element = self.next
while element != self:
yield element.value
element = element.next
def __str__(self):
"""
Returns a string representing the set.
"""
return ("{{{}}}".format(", ".join(map(str, self.getElements()))))
def __repr__(self):
"""
Represents the set.
"""
return str(self)