-
Notifications
You must be signed in to change notification settings - Fork 0
/
disjointSetClass2.py
83 lines (77 loc) · 2.52 KB
/
disjointSetClass2.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
81
82
83
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 14 13:38:43 2021
@author: shrohanmohapatra
"""
class disjointSetNew:
def __init__(self):
self.forest = {}
def MakeSet(self,x):
if x not in self.forest:
self.forest[x] = {}
self.forest[x]['parent'] = x
self.forest[x]['size'] = 1
self.forest[x]['rank'] = 0
def Find(self, x):
root = x
while self.forest[root]['parent']!=root:
root = self.forest[root]['parent']
while self.forest[x]['parent']!=root:
parent = self.forest[x]['parent']
self.forest[x]['parent'] = root
x = parent
return root
def UnionBySize(self,x,y):
xRoot = self.Find(x)
yRoot = self.Find(y)
self.forest[x] = self.forest[xRoot]
self.forest[y] = self.forest[yRoot]
if self.forest[x] == self.forest[y]: return
if self.forest[x]['size'] < self.forest[y]['size']:
(self.forest[x],self.forest[y]) = (self.forest[y], \
self.forest[x])
self.forest[y]['parent'] = x
self.forest[x]['size'] = self.forest[x]['size'] + \
self.forest[y]['size']
def UnionByRank(self,x,y):
xRoot = self.Find(x)
yRoot = self.Find(y)
self.forest[x] = self.forest[xRoot]
self.forest[y] = self.forest[yRoot]
if self.forest[x] == self.forest[y]: return
if self.forest[x]['rank'] < self.forest[y]['rank']:
(self.forest[x],self.forest[y]) = (self.forest[y], \
self.forest[x])
self.forest[y]['parent'] = x
self.forest[x]['rank'] = self.forest[x]['rank'] + 1
# Some elementary basic checks whether they work with the code
# that works for the class definition
print('Some elementary basic checks ...')
A = {1:'a',2:'b',3:'c'}
B = {1:'a',2:'b',3:'d'}
print(A==B)
B = A
print(A==B)
a = 4
b = 6
print(a,b)
(a, b) = (b, a)
print(a,b)
print('Now let us test the disjoint set data structure ...')
newMarrion = disjointSetNew()
for k in range(1,11):
print('Adding k =',k,' to the set!')
newMarrion.MakeSet(k)
print(newMarrion.forest)
for k in range(1,5):
print('Unifying',2*k-1,'and',2*k)
newMarrion.UnionByRank(2*k-1, 2*k)
print(newMarrion.forest)
from time import time
for k in range(1,11):
start = time()
s1 = newMarrion.Find(k)
end = time()
print('Finding ',k,'and found',s1)
print('Time taken = ',(end-start)*10**6,'usecs')