题意:有n个学生,给出其中m对具有相同信仰的学生。求所有学生可能的最大的信仰数量。
思路:采用并查集。
输入:
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
输出:
Case 1: 1
Case 2: 7
#include <stdio.h>
#include <string.h>
#define N 50002
int n,m,res,T = 0;
int father[N];
int find(int x){
if(father[x] == x)
return x;
return father[x] = find(father[x]);
}
void merge(int x,int y){
int xx = find(x);
int yy = find(y);
if(xx != yy)
father[yy] = xx;
}
int main(){
freopen("a.txt","r",stdin);
while(scanf("%d %d",&n,&m)){
int i,j;
if(!n&&!m)
break;
++T;
for(i = 1;i<=n;i++)
father[i] = i;
while(m--){
scanf("%d %d",&i,&j);
merge(i,j);
}
res = n;
for(i = 1;i<=n;i++){
if(find(i)!=i)//如果标号与原始标号不同,表示该学生与其他某学生具有相同信仰
res--;
}
printf("Case %d: %d\n",T,res);
}
}