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
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
题意:
一个学校的学生信仰宗教的最大种类数。已知学生总数及同一信仰的两个学生号。
分析:
并查集的简单应用,将同一信仰的两个学生合并。求得共有多少个分组,未提及的学生自成一组,算得最大种类数。
#include <stdio.h>
int rankk[100001];
int F[100001];
int findd(int n)
{
int root=n;
while(root!=F[root])
root=F[root];
return root;
}
void unionn(int x,int y)
{
int root1,root2;
root1=findd(x);
root2=findd(y);
if(root1!=root2)
F[root1]=root2;
}
int main()
{
int m,n,i,x,y,t=0;
while(1)
{
t++;
int s=0;
scanf("%d%d",&n,&m);
if(n==0&&m==0)
break;
for(i=1;i<=n;i++)
F[i]=i;
for(i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
unionn(x,y);
}
for(i=1;i<=n;i++)
if(F[i]==i)
s++;
printf("Case %d: %d\n",t,s);
}
return 0;
}