You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classUnionFindSet {
public:UnionFindSet(int n) {
ranks_ = vector<int>(n + 1, 0);
parents_ = vector<int>(n + 1, 0);
for (int i = 0; i < parents_.size(); ++i)
parents_[i] = i;
}
// Merge sets that contains u and v.// Return true if merged, false if u and v are already in one set.boolUnion(int u, int v) {
int pu = Find(u);
int pv = Find(v);
if (pu == pv) returnfalse;
// Meger low rank tree into high rank treeif (ranks_[pv] < ranks_[pu])
parents_[pv] = pu;
elseif (ranks_[pu] < ranks_[pv])
parents_[pu] = pv;
else {
parents_[pv] = pu;
ranks_[pu] += 1;
}
returntrue;
}
// Get the root of u.intFind(int u) {
// Compress the path during traversalif (u != parents_[u])
parents_[u] = Find(parents_[u]);
return parents_[u];
}
private:
vector<int> parents_;
vector<int> ranks_;
};
The text was updated successfully, but these errors were encountered:
DFS 和 Union-Find
Union-Find实现原理:
The text was updated successfully, but these errors were encountered: