Union-find implementation [00PC]
Based on the above ideas, we can implement a union-find structure as follows.
- We keep track of an array/dictionary mapping each item to its parent. Any item which maps to itself is considered a "root". This represents a forest, that is, a collection of trees; each tree consists of items which are all in the same set.
- We also keep track of an array/dictionary mapping every root item to the height of its tree. Tracking the heights of the trees is important so that we can implement union in a reasonable way. Non-root items will be ignored, so it does not matter what they map to. In other words, once an item stops being a root, we will stop worrying about keeping its height updated.
Given these mappings, we can implement the union-find operations as follows.
- To create a fresh union-find structure, create the parent dictionary mapping every item to itself (since every item starts in its own singleton set), and the height dictionary mapping every item to 0 (every item is the root of its own trivial tree of height 0).
- To implement \mathsf {Find}(u), repeatedly finding the parent, grandparent, etc. of u until finding a root.
- To implement \mathsf {Union}(u,v):
- Use \mathsf {Find} to get the roots of u and v’s trees.
- If the roots are the same, do nothing.
- If the roots are different, make the root with the smaller height the child of the root with the bigger height. If the heights are the same, it doesn’t matter which becomes a child of the other, but you must then increment the height of the new parent.