this is the code for findind disjoint sets
class disjoint_sets {
struct disjoint_set {
size_t parent;
unsigned rank;
disjoint_set(size_t i) : parent(i), rank(0) { }
};
std::vector<disjoint_set> forest;
public:
disjoint_sets(size_t n){
forest.reserve(n);
for (size_t i=0; i<n; i++)
forest.push_back(disjoint_set(i));
}
size_t find(size_t i){
if (forest[i].parent == i)
return i;
else {
forest[i].parent = find(forest[i].parent);
return forest[i].parent;
}
}
void merge(size_t i, size_t j) {
size_t root_i = find(i);
size_t root_j = find(j);
if (root_i != root_j) {
if (forest[root_i].rank < forest[root_j].rank)
forest[root_i].parent = root_j;
else if (forest[root_i].rank > forest[root_j].rank)
forest[root_j].parent = root_i;
else {
forest[root_i].parent = root_j;
forest[root_j].rank += 1;
}
}
}
};
why are we incrementing rank if ranks are eqaul???nma beginner sorry and also what is the find step doing??
Because in this case - you add one tree is a "sub tree" of the other - which makes the original subtree increase its size.
Have a look at the following example:
1 3
| |
2 4
In the above, the "rank" of each tree is 2.
Now, let's say 1 is going to be the new unified root, you will get the following tree:
1
/ \
/ \
3 2
|
4
after the join the rank of "1" is 3, rank_old(1) + 1
- as expected.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.