1- class UnionFind :
1+ """
2+ This module implements a Union-Find (Disjoint Set Union) data structure.
3+ It provides methods to find the root of an element and to union two elements.
4+ It is useful for efficiently managing and merging disjoint sets.
5+ """
26
3- def __init__ (self , X ):
4- self ._parent = {x : x for x in X }
7+ from typing import Dict , Generic , Iterable , TypeVar
8+
9+ T = TypeVar ("T" )
10+
11+
12+ class UnionFind (Generic [T ]):
13+ """
14+ A Union-Find data structure for managing disjoint sets.
15+ It supports efficient union and find operations, allowing for the
16+ merging of sets and finding the root representative of an element.
17+ It is particularly useful in algorithms that require dynamic connectivity,
18+ such as Kruskal's algorithm for minimum spanning trees or in network connectivity problems.
19+
20+ :param X: An iterable containing the initial elements to be managed by the Union-Find structure.
21+ :type X: iterable
22+ """
23+
24+ def __init__ (self , X : Iterable [T ]):
25+ self ._parent : Dict [T , T ] = {x : x for x in X }
526 self ._size = {x : 1 for x in X }
627
7- def find (self , x ):
28+ def find (self , x : T ) -> T :
29+ """
30+ Finds the root representative of the set containing element x.
31+ This method implements path compression to flatten the structure,
32+ making future queries faster by ensuring that all elements point directly to the root.
33+ :param x: The element whose root representative is to be found.
34+ :type x: Any
35+ :return: The root representative of the set containing x.
36+ :rtype: Any
37+ """
838 root = x
939 while root != self ._parent [root ]:
1040 root = self ._parent [root ]
@@ -15,7 +45,19 @@ def find(self, x):
1545 tmp = parent
1646 return root
1747
18- def union (self , x , y ):
48+ def union (self , x : T , y : T ) -> T :
49+ """
50+ Unites the sets containing elements x and y.
51+ If the elements are already in the same set, no action is taken.
52+ If they are in different sets, the smaller set is merged into the larger set,
53+ ensuring that the root of the larger set becomes the new root representative.
54+ :param x: The first element to be united.
55+ :param y: The second element to be united.
56+ :type x: Any
57+ :type y: Any
58+ :return: The root representative of the united set.
59+ :rtype: Any
60+ """
1961 x , y = self .find (x ), self .find (y )
2062 if x != y :
2163 x_size , y_size = self ._size [x ], self ._size [y ]
0 commit comments