The Suspects
题意
在一个学校,一共有N个学生,他们组建了M个小组,现在有一个人中了病毒,具有传染性,与感染者同组人员都会被传染,问最终会传染多少人?
分析
使用并查集,把有联系的人都合并起来,最后压缩一边路径,看其id号为0的点有多少个就可以了
AC 代码
#include <iostream>
#include <stdio.h>
using namespace std;
typedef long long ll;
const int maxn = 3e4+10;
int N,M;
int fa[maxn];
int arr[maxn];
void init(){
for(int i = 0;i<N;i++) fa[i] = i;
}
int find(int x){
if(x != fa[x])
fa[x] = find(fa[x]);
return fa[x];
}
void join(int x,int y){
int fx = find(x),fy = find(y);
if(fx != fy){
if(fx == 0) fa[fy] = fx;
else fa[fx] = fy;
}
}
int main(){
while(scanf("%d %d",&N,&M)){
if(N == 0 && M == 0) break;
init();
while (M--){
int k;
scanf("%d",&k);
for(int i = 0;i<k;i++) {
scanf("%d",&arr[i]);
if(i) join(arr[i-1],arr[i]);
}
}
for(int i = 0;i<N;i++) find(i);//把所有的路径都压缩一下
int res = 0;
for(int i = 0;i<N;i++)
if(fa[i] == 0){
res++;
}
printf("%d\n",res);
}
return 0;
} 
京公网安备 11010502036488号