Union
Assume we initialize each node’s parent is itself. root[i] = i
Union operation is just to set one root to be a child of another root.
1 | void union_root(int x, int y) { |
Find
The plain version is to find root of its parent until its parent is itself.
1 | int find_root(int x) { |
Path compression (No reason not to use.)
1 | int find_root(int x) { |
or1
2
3
4
5
6
7int find_root(int x) {
while (x!=root[x]) {
root[x] = root[root[x]];
x = root[x];
}
return root[x];
}