标签:并查集
**Ubiquitous Religions**
Description
There are so many different religions in the world today that it is difficult to keep track of them all. You are interested in finding out how many different religions students in your university believe in.
You know that there are n students in your university (0 < n <= 50000). It is infeasible for you to ask every student their religious beliefs. Furthermore, many students are not comfortable expressing their beliefs. One way to avoid these problems is to ask m (0 <= m <= n(n-1)/2) pairs of students and ask them whether they believe in the same religion (e.g. they may know if they both attend the same church). From this data, you may not know what each person believes in, but you can get an idea of the upper bound of how many different religions can be possibly represented on campus. You may assume that each student subscribes to at most one religion.
Input
The input consists of a number of cases. Each case starts with a line specifying the integers n and m. The next m lines each consists of two integers i and j, specifying that students i and j believe in the same religion. The students are numbered 1 to n. The end of input is specified by a line in which n = m = 0.
Output
For each test case, print on a single line the case number (starting with 1) followed by the maximum number of different religions that the students in the university believe in.
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
题目大意:世界上宗教何其多。假设你对自己学校的学生总共有多少种宗教信仰很感兴趣。学校有m个学生,但是你不能直接问学生的信仰,不然他会感到很不舒服的。有另外一个方法是问n对同学,是否信仰同一宗教。根据这些数据,计算学校最多有多少种宗教信仰的。
解题思路: 很明显使用并查集啊。。。。就是,让一个数ans开始ans == m,然后就一直找,当发现有一对学生信仰听一个信仰的时候就ans--,,,具体详见代码。。。。。
上代码:
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 50000+5;
int fa[maxn], rank[maxn];
int m, n, ans;
void Init(int x)
{
for(int i=0; i<=x; i++)
{
fa[i] = i;
rank[i] = 1;
}
}
int Find(int x)
{
if(x != fa[x])
fa[x] = Find(fa[x]);
return fa[x];
}
void Union(int x, int y)
{
int fx = Find(x);
int fy = Find(y);
if(fx == fy)
return ;
else
{
if(rank[fx] > rank[fy])
{
fa[fy] = fx;
//sum[fx] += sum[fy];
}
else
{
fa[fx] = fy;
if(rank[fx] == rank[fy])
rank[fy]++;
//sum[fy] += sum[fx]
}
}
ans--;
}
int main()
{
int j=1;
while(~scanf("%d%d",&m,&n))
{
if(m==0 && n==0)
break;
Init(m);
int x, y;
ans = m;
while(n--)
{
scanf("%d%d",&x, &y);
Union(x, y);
}
printf("Case %d: %d\n", j++, ans);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:并查集
原文地址:http://blog.csdn.net/qingshui23/article/details/47396147