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

POJ2524——宗教(Ubiquitous Religions)【图论,并查集】

2018-03-23 18:55 501 查看

正题

题目链接:

http://poj.org/problem?id=2524

大意

有n个学生,告诉你哪两个学生的宗教相等,求校园里有多少个宗教。

解题思路

并查集链接就好了

代码

#include<cstdio>
using namespace std;
int n,m,x,y,s,father[50001],t;
int find(int x)
{
if (x!=father[x]) return father[x]=find(father[x]);
else return father[x];
}//寻找祖先
int unionn(int x,int y)
{
int fa=find(x),fb=find(y);
if (fa<fb) father[fb]=fa;
else father[fa]=fb;
}//连接
int main()
{
while (true)
{
scanf("%d%d",&n,&m);
if (n==0) break;
t++;
s=0;
for (int i=1;i<=n;i++) father[i]=i;
for (int j=1;j<=m;j++)
{
scanf("%d%d",&x,&y);
unionn(x,y);//连接
}
for (int i=1;i<=n;i++)
if (father[i]==i) s++;//统计
printf("Case %d: %d\n",t,s);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: