考前训练之并查集:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int MAX = 1010;
vector<int> firsthob;
int father[MAX];
int root[MAX]={0};
void initfather(){
for(int i=0;i<MAX;i++){
father[i]=i;
}
}
int findfather(int x){
if(x==father[x]) return x;
else{
int F=findfather(father[x]);
father[x]=F;
return F;
}
}
void Union(int a,int b){
int Afa=findfather(a);
int Bfa=findfather(b);
if(Afa!=Bfa){
father[Afa]=Bfa;
}
}
bool compare(int a,int b){
if(a>b) return true;
else return false;
}
int main(){
initfather();
int n;
cin>>n;
for(int i=0;i<n;i++){
int numhobs,tempfirsthob;
scanf("%d",&numhobs);
getchar();
getchar();
scanf("%d",&tempfirsthob);
firsthob.push_back(tempfirsthob);
for(int j=0;j<numhobs-1;j++){
int temphob;
scanf("%d",&temphob);
Union(tempfirsthob,temphob);
}
}
for(int i=0;i<n;i++){
int temproot=findfather(firsthob[i]);
root[temproot]++;
}
sort(root,root+MAX,compare);
int count=0;
while(root[count++]!=0);
count--;
cout<<count<<endl;
for(int i=0;i<count;i++){
if(i!=0) printf(" ");
printf("%d",root[i]);
}
}
并查集算法详解与应用
本文详细介绍了并查集算法的基本概念、实现原理及应用案例。通过具体代码实例展示了如何利用并查集解决实际问题,包括初始化、查找、合并等核心操作。
4396

被折叠的 条评论
为什么被折叠?



