File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ class ForestOfTrees :
2
+ def __init__ (self ):
3
+ self .sets = []
4
+ self .ranks = []
5
+
6
+ def make_set (self , x ):
7
+ self .sets .append (x )
8
+ self .ranks .append (x )
9
+
10
+ def union (self , x , y ):
11
+ self .link (self .find_set (x ), self .find_set (y ))
12
+
13
+ def link (self , x , y ):
14
+ if self .ranks [x ] > self .ranks [y ]:
15
+ self .sets [y ] = x
16
+ else :
17
+ self .sets [x ] = y
18
+ if self .ranks [x ] == self .ranks [y ]:
19
+ self .ranks [y ] += 1
20
+
21
+ def find_set (self , x ):
22
+ if x != self .sets [x ]:
23
+ self .sets [x ] = self .find_set (self .sets [x ])
24
+ return self .sets [x ]
25
+
26
+ def print_tabs (self , how_many ):
27
+ for disjoint in range (how_many ):
28
+ while self .sets [disjoint ] != disjoint :
29
+ print (str (disjoint ) + " -> " , end = "" )
30
+ disjoint = self .sets [disjoint ]
31
+ print (disjoint )
32
+
33
+
34
+ if __name__ == "__main__" :
35
+ trees = ForestOfTrees ()
36
+ how_many_sets = 6
37
+ for x in range (how_many_sets ):
38
+ trees .make_set (x )
39
+ trees .union (0 , 4 )
40
+ trees .union (1 , 3 )
41
+ trees .union (1 , 5 )
42
+ trees .print_tabs (how_many_sets )
You can’t perform that action at this time.
0 commit comments