这是查找不相交集的代码
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;
}
}
}
};
如果排名是 eqaul,为什么我们要增加排名???nma 初学者对不起,查找步骤在做什么?