您的位置:首页 > 产品设计 > UI/UE

poj 2504 Ubiquitous Religions

2010-10-17 18:21 260 查看
题意:宗教信仰的引题,首先告诉我们相互认识的两个人有相同的信仰。

解题思路:比较简单的并查集入门。

代码:

#include <iostream>
using namespace std;

const int MAX = 50005;
int father[MAX],num[MAX];
int n,output;
//father[i] 保存的是i的父亲节点。num【i】中保存的是 这个集合里面从i开始下面有多少个数+自己
void init()
{
for(int i = 0 ; i <=n ; i++)
{
father[i] = i;
num[i] = 1;
}
}
int find(int x)
{
if(x!=father[x])
father[x] = find(father[x]);
return father[x];
}
void unions(int a,int b)
{
int x = find(a);
int y = find(b);
if(x==y)
return ;
else
if(num[x] <= num[y])
{
father[x] = y;
num[y] += num[x];
output--;
}
else
{
father[y] = x;
num[x] += num[y];
output--;
}
}

int main()
{
int x,y,m;
int cas=1;
while(scanf("%d%d",&n,&m) , n||m)
{
output = n;
init();
while(m--)
{
scanf("%d%d",&x,&y);
unions(x,y);
}
printf("Case %d: %d/n",cas,output);
cas++;

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: