POJ2524 并查集
#include<iostream>
using namespace std;
int father[50005];
int rank[50005];
int maxNum;
void make_set(int x){
father[x]=x;
rank[x]=1;
}
int find_set(int x){
if(x!=father[x])
{
father[x]=find_set(father[x]);
}
return father[x];
}
void Union(int x,int y){
x=find_set(x);
y=find_set(y);
if(x==y) return;
if(rank[x]<=rank[y]){
father[x]=y;
rank[y]+=rank[x];
maxNum--; //每合并一次总数减一
}
else{
father[y]=x;
rank[x]+=rank[y];
maxNum--;
}
}
int main(){
int m,n;
int i,j;
int x,y;
int Case=1;
freopen("acm.txt","r",stdin);
cin>>n>>m;
while(n){
maxNum=n;
for(i=n;i>0;i--)
make_set(i);
for(j=m;j>0;j--){
cin>>x>>y;
Union(x,y);
}
cout<<"Case "<<Case<<": "<<maxNum<<endl;
cin>>n>>m;
Case++;
}
return 0;
}
我是一名在校大学生,热爱编程,虽然起步晚了些,但我会努力的。呵呵!
数据结构 算法

浙公网安备 33010602011771号