class unionset{
private:
int setn;
vector<int> parent;
vector<int> nums;
public:
unionset(n):setn(n),parent(n),nums(n,1){
iota(parent.begin(),parent.end(),0);
}
bool find(int x){
return (x==parent[x]?x:parent[x]=find(parent[x]));
}
bool union(int x,int y) {
if (isconnected(x,y))
return false;
x = find(x);
y = find(y);
if(nums[x]<nums[y])
swap(x,y);
parent[y]=x;
nums[x]+=nums[y]
setn--;
return true;
}
bool isconnected(int x,int y){
return (find(x)==find(y));
}
}
并查集做题模板
最新推荐文章于 2024-11-15 16:27:37 发布