并查集必背模板
class UnionFind{
public:
UnionFind(int n){
parent = vector<int>(n);
rank = vector<int>(n);
for(int i = 0; i < n; i++)
parent[i] = i;
}
void uni(int x, int y)
{
int rootx = find(x);
int rooty = find(y);
if(rootx != rooty){
if(rank[rootx] > rank[rooty])
parent[rooty] = rootx;
else if(rank[rootx] < rank[rooty])
parent[rootx] = rooty;
else {
parent[rooty] = rootx;
rank[rootx]++;
}
}
}
int find(int x)
{
if(parent[x] != x)
parent[x] = find(parent[x]);
return parent[x];
}
private:
vector<int> parent;
vector<int> rank;
};
本文来自博客园,作者:静候佳茵,转载请注明原文链接:https://www.cnblogs.com/hitwherznchjy/p/16540687.html