您的位置:首页 > 其它

POJ2524 并查集

2012-01-19 16:10 302 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: