Chapter 5 Disjoint Set
Equivalence Relations
The Dynamic Equivalence Problem
- Elements: 1, 2, …, N
- Sets: disjoint
Operations
- Union(i, j)
- Find(i)
Basic Data Structure
Union
set the parent pointer of one of the roots to the other root
Implementation
// Linked List is bad!!! |
typedef struct SetStruct* Set; |
always
Find
Implementation
Set Find(int key, Set sets[], int size); // Linked List is bad!!! |
int Find(int key, Set set){ |
Analysis
Union-Find Operation
try Union(2, 1) find(1);
Union(3, 2) find(2);
…
Union(N + 1, N) find(N);
then, the tree becomes a linked list while the time complexity becomes
Smart Union Algorithms
Union by Size
Always union the smaller tree to the larger one
Define set->root[root] = -Size
Make the signal bit of the root ndoe to represent the size of the tree
Initialize all signal bit by -1
When trying to Union Set i and Set j, always let the Set with larger size unioned by the one with smaller size
Now the time complexity reduces to
Lemma Let T be a tree created by union-by-size with N nodes, then
the worst case is binary tree, while the best case is 1 root node with (N - 1) leaf nodes
time complexity of N union and M find:
Union by Height
Always union the shallower tree to the deeper one
Path Compression
int Find(int key, Set set){ |
int Find(int key, Set set){ |
Only can be used with Union-by-Size, because path compression will change the height of the tree, we need to change the height frequantly
Worst Case For Union-by-Rank and Path Compression
Lemma(Tarjan)
Ackermann’s Function
for common M and N,
: inverse Ackermann’s Function
So can be taken as a const number
While are const numbers, the final time complexity is