算法笔记一道并查集题目的算法实现

 

 

 

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#define maxn 100+5
int father[maxn];
int isRoot[maxn];
vector <int> v;
int getTop(int x){
if (x==father[x])
return x;
else
return getTop(father[x]);
}
void unity(int x,int y){
int a=getTop(x);
int b=getTop(y);
if (a!=b){
father[a]=b;
isRoot[b]+=isRoot[a];
isRoot[a]=0;
}
return;
}
int main(){
fill(isRoot,isRoot+maxn,1);
int N,M;
scanf("%d%d",&N,&M);
int x,y;
for (int i=1;i<=N;i++){
father[i]=i;
}
for (int i=0;i<M;i++){
scanf("%d%d",&x,&y);
unity(x,y);
}
int sum=0;
for (int i=1;i<=N;i++){
if (isRoot[i]){
v.push_back(isRoot[i]);
sum++;
}
}
cout<<sum<<endl;
for(int i=0;i<v.size();i++){
printf("%d%c",v[i],i!=v.size()-1?' ':'\n');
}
return 0;
}
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!样例1
输入
4 2
1 4
2 3

输出
2
2 2
*/
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!样例2
输入
1 2
2 3
3 1
1 4
5 6

输出
3
4 2 1
*/

posted @ 2018-06-21 12:29  执蘖执蘖  阅读(113)  评论(0编辑  收藏  举报