标签:
链接:http://poj.org/problem?id=2524
| Time Limit: 5000MS | Memory Limit: 65536K | |
| Total Submissions: 27774 | Accepted: 13610 |
Description
Input
Output
Sample Input
10 9
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
10 4
2 3
4 5
4 8
5 8
0 0
Sample Output
Case 1: 1
Case 2: 7
Hint
题意:一学生想知道学校学生信仰的宗教种类有多少个,于是在总学生数为n中,他调查了m对,最后输出不同宗教的总数。
解题思路:很明显用并差集。我们只要将N位学生划分成集合,信仰同一个宗教的放在同一个集合中,最终集合个数就是不同宗教的个数,即问题转换成求有多少个不同的集合。
<span style="font-size:18px;">#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=50010;
int father[maxn],rank[maxn];
int b[maxn];
int find(int x) //父节点查找
{
if(x==father[x]) return x;
else return father[x]=find(father[x]);
}
void unite(int x,int y)//集合合并
{
int fx=find(x);
int fy=find(y);
if(fx==fy) return;
if(rank[fx]>rank[fy])
{
father[fy]=fx;
}
else{
father[fx]=fy;
if(rank[fx]==rank[fy])
rank[fy]++;
}
}
int main()
{
int x,y,n,m,cas=0;
while(scanf("%d %d",&n,&m) && n+m)
{
for(int i=1;i<=n;i++) {father[i]=i;rank[i]=0;}
while(m--)
{
scanf("%d %d",&x,&y);
unite(x,y);
}
for(int i=1;i<=n;i++)
b[i]=find(i);//刚开始fing(i)我写成成了father[i],,结果WA了五六次,在这大家共勉下
sort(b+1,b+n+1);
int ans=1;
for(int i=2;i<=n;i++)
if(b[i] != b[i-1]) ++ans;
printf("Case %d: %d\n",++cas,ans);
}
return 0;
}
</span>版权声明:本文为博主原创文章,转载记得著名出处,谢谢!
POJ 2524 Ubiquitous Religions(宗教种类:并差集)
标签:
原文地址:http://blog.csdn.net/hellohelloc/article/details/48102437