F - Ubiquitous Religions
题目描述:
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:
Sample Output:
题目给的提示:
题目大意:
学校调查学生中有多少个宗教群体,但是不好意思直接去问(这有什么不好意思的)吐槽一下,所以他们想到一个间接问法,如果A同学信佛教,问B同学是不是和A同学是一样的宗教,然后依次类推,问C同学。
最后得出有多少个宗教群体。当输入为0 0的时候,就退出程序。
思路分析:
这道题是很典型的查并行,直接将每一个同学创一个父子集,如果遇到相同的,例如A与B,就将B改成A的父子集,依次类推,这里可以右变化也可以左变化,右变化就是A改成B的父子集。
代码块:
#include<stdio.h>
int f[50005];
int lemon2(int b);
void lemon(int b)//为每一个单位(同学)创造父子集
{
int c;
for(c=1;c<=b;c++)
{
f[c]=c;
}
}
void lemon1(int d,int e)//开始改变子集
{
int t1,t2;
t1=lemon2(d);//返回d的父子集
t2=lemon2(e);//返回e的父子集
if(t1!=t2)//如果他们不相同,就改变他们其中一者的父子集,这里是左变化。
{
f[t2]=t1;
}
}
int lemon2(int b)//寻找父子集
{
if(f[b]==b)//如果等于本身,说明还未改变父子集
{
return f[b];
}
return lemon2(f[b]);//如果不等于本身,说明已经改变,继续递归找出父子集
}
int main()
{
int a,b,c,d,e,g=1;
while(scanf("%d %d",&b,&c)!=EOF)
{
int num=0;
if(b==0 && c==0)
return 0;
lemon(b);
for(a=0;a<c;a++)
{
scanf("%d %d",&d,&e);
lemon1(d,e);
}
for(a=1;a<=b;a++)//划分子集群体。
{
if(f[a]==a)
num++;
}
printf("Case %d: %d\n",g++,num);
}
}