Disjoint sets are a data structure that extends the functionality of sets by maintaining multiple disjoint subsets of elements, i.e., a disjoint set with two subsets have:
These find considerable use in graph problems, especially in applying the basic union and find operations (union-find algorithm).
Union-find
Union-find maintains a few structures:
- The array
link[]
contains for each element, the next element in the chain. At the beginning, thelink[i]
containsi
. - The array
size[]
contains the size of each subset, given thei
-th element.
There are also two main functions:
- The
find()
algorithm returns the representative for an elementx
, which can be found by following the chain that begins atx
. - The
unite()
function joins the initially disjoint sets that contains elements and . It finds the representatives of the subsets, then connects the smaller set to the larger set.