forked from herrmendez/python-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickunion.py
42 lines (31 loc) · 969 Bytes
/
quickunion.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
from utils.benchmark import *
class QuickUnionUF(object):
id = []
def __init__(self, n=None, arr=None):
if arr == None:
self.id = self._constuct_array(n)
else:
self.id = arr
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)
self.id[i] = j
if __name__ == '__main__':
from test_quickalgo import test
tree = random_tree(1000000)
arr = [QuickUnionUF]
test(arr, tree)