forked from herrmendez/python-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickunion_weighted.py
57 lines (46 loc) · 1.67 KB
/
quickunion_weighted.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
from utils.benchmark import *
class QuickUnionWeighted(object):
id = []
sz = [] # keep track on the number of objects of each tree
def __init__(self, n=None, arr=None):
if arr == None:
self.id = self._constuct_array(n)
else:
self.id = arr
self.sz = [0]*len(self.id) # faster than [0 for e in range(len(self.id)+1)]
def _constuct_array(self, n):
temp_arr = []
for e in range(n):
temp_arr.append(e)
return temp_arr
def _get_root(self, el):
'''check parents pointer until reach root'''
while el != self.id[el]:
el = self.id[el]
return el
def connected(self, p, q):
'''check if they share the same root'''
return self._get_root(p) == self._get_root(q)
def union(self, p, q):
'''change root of p to point to root of q'''
i = self._get_root(p)
j = self._get_root(q)
# check if the tree rooted at i is smaller than the one rooted at j
if self.sz[i] < self.sz[j]:
self.id[i] = j
self.sz[j] += self.sz[i]
else:
self.id[j] = i
self.sz[i] += self.sz[j]
class QuickUnionPathCompression(QuickUnionWeighted):
def _get_root(self, el):
'''get roots and flatten the tree by pointing the nodes to the root directly'''
while el != self.id[el]:
self.id[el] = self.id[self.id[el]] # point node to root id
el = self.id[el]
return el
if __name__ == '__main__':
from test_quickalgo import test
tree = random_tree(1000000)
arr = [QuickUnionWeighted, QuickUnionPathCompression]
test(arr, tree)