西窗月

Disjoint-set (union find)

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
2
3
4
5
6
7
void union_root(int x, int y) {
int r1 = find_root(x);
int r2 = find_root(y);
if (r1 != r2) {
root[r1] = r2;
}
}

Find

The plain version is to find root of its parent until its parent is itself.

1
2
3
4
5
6
int find_root(int x) {
if (x!=root[x]) {
return find_root(root[x]);
}
return root[x];
}

Path compression (No reason not to use.)

1
2
3
4
5
6
int find_root(int x) {
if (x!=root[x]) {
root[x] = find_root(root[x]);
}
return root[x];
}

or

1
2
3
4
5
6
7
int find_root(int x) {
while (x!=root[x]) {
root[x] = root[root[x]];
x = root[x];
}
return root[x];
}

Reference

  1. princeton slide