-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisjointset.py
67 lines (45 loc) · 1.22 KB
/
disjointset.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
class Node:
def __init__(self,x):
self.val = x
self.parent = self
self.rank = 0
def __str__(self):
return str(self.val)
class DisjointSets:
def makeset(self,x):
return Node(x)
def findset(self,p):
if p.parent!=p:
p.parent=self.findset(p.parent)
return p.parent
def union(self,x,y):
rootx=self.findset(x)
# print("%%%%",rootx)
# print("$$$",rootx.rank)
rooty=self.findset(y)
# print("(((",rooty)
# print("$$$",rootx.rank)
if(rootx==rooty):
return
if(rootx.rank>rooty.rank):
rooty.parent=rootx
elif(rootx.rank<rooty.rank):
rootx.parent=rooty
else:
rootx.parent=rooty
rooty.rank=rooty.rank+1
def main():
ds = DisjointSets()
nodes = []
for i in range(10):
node = ds.makeset(i)
nodes.append(node)
print("%%%",nodes)
print(ds.findset(nodes[0]))
ds.union(nodes[0],nodes[1])
print(ds.findset(nodes[0]))
ds.union(nodes[0],nodes[2])
print(ds.findset(nodes[2])) # Should print 1
''' Add more tests!'''
if __name__ == '__main__':
main()