并查集Union Find
UF
class UF{
public:
explicit UF(int number);
int find(int x);
bool connected(int x, int y);
void unions(int x, int y);
private:
vector<int> id;
vector<int> rank;
}
UF::UF(int number){
id.resize(number);
iota(id.begin(),id.end(),0);
rank.resize(number,1);
}
int UF::find(int x){
while(id[x]!=x)
x=find(id[x]);
return id[x];
}
bool UF:: connected(int x,int y){
return find(x)==find(y);
}
void UF::unions(int x, int y){
int root1=find(x);
int root2=find(y);
if(root1==root2) return;
if(rank[root1]<rank[root2]){
id[root1]=root2;
rank[root2]+=rank[root1];
}else{
id[root2]=id[root1];
rank[root1]+=rank[root2];
}
}
Number of Connected Components in an Undirected Graph
int countComponents(int n,vector<pair<int, int>>& edges){
int cnt=0;
UF(n);
for(auto edge:edges)
unions(edge.first,edge.second);
for(int i=0;i<n;i++)
if(id[i]==i)
cnt++;
return cnt;
}
Graph Valid Tree
- 考察一:无环图
- 考察二:树的边的个数edges=vertices-1
bool ValidTree(int n, vector<pair<int, int>>& edges){
if(edges.empty() || edges.size()!=n-1) return false;
UF(n);
for(auto edge:edges){
int x=find(edge.first);
int y=find(edge.second);
if(x==y) return false;
id[x]=y;
}
return true;
}