[英]disjoint set data structure
this is the code for findind disjoint sets 这是findind不交集的代码
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?? 如果等级为eqaul,为什么我们要增加等级?? nma初学者不好意思,查找步骤在做什么?
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. 在上面,每棵树的“等级”是2。
Now, let's say 1 is going to be the new unified root, you will get the following tree: 现在,假设1将成为新的统一根,您将获得以下树:
1
/ \
/ \
3 2
|
4
after the join the rank of "1" is 3, rank_old(1) + 1
- as expected. 加入后,“ 1”的等级为3, rank_old(1) + 1
如预期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.