Week6 B - 戴好口罩!
新型冠状病毒肺炎(Corona Virus Disease 2019,COVID-19),简称“新冠肺炎”,是指2019新型冠状病毒感染导致的肺炎。
如果一个感染者走入一个群体,那么这个群体需要被隔离!
小A同学被确诊为新冠感染,并且没有戴口罩!!!!!!
危!!!
时间紧迫!!!!
需要尽快找到所有和小A同学直接或者间接接触过的同学,将他们隔离,防止更大范围的扩散。
众所周知,学生的交际可能是分小团体的,一位学生可能同时参与多个小团体内。
请你编写程序解决!戴口罩!!
Input
多组数据,对于每组测试数据:
第一行为两个整数n和m(n = m = 0表示输入结束,不需要处理),n是学生的数量,m是学生群体的数量。0 < n <= 3e4 , 0 <= m <= 5e2
学生编号为0~n-1
小A编号为0
随后,m行,每行有一个整数num即小团体人员数量。随后有num个整数代表这个小团体的学生。
Output
输出要隔离的人数,每组数据的答案输出占一行
Sample Input
100 4
2 1 2
5 10 13 11 12 14
2 0 1
2 99 2
200 2
1 5
5 1 2 3 4 5
1 0
0 0
Sample Output
4
1
1
解题思路
用数组模拟
输入时合并(unite)
最后find(0)找感染者在的那棵树
Code
#include<iostream>
#include<iostream>
#include<vector>
#include<string.h>
#include<algorithm>
using namespace std;
int m,n,num;
int s[100000];
int rs[100000];
void init(int x){
for(int i=0;i<x;i++){
s[i]=i;rs[i]=1;
}
}
int find(int x){
if(s[x]==x) return x;
return find(s[x]);
}
bool unite(int x,int y){
x=find(x);y=find(y);
if(x==y)return false;
if(rs[x]>rs[y]){s[y]=x;rs[x]=(rs[y]+=rs[x]);
}else{s[x]=y;rs[y]=(rs[x]+=rs[y]);
}
return true;
}
int main(){
int ans;
while(cin>>n>>m){if(n==0&&m==0)return 0;
init(n);
for(int i=0;i<m;i++){
cin>>num;
int f;
cin>>f;
for(int i=1;i<num;i++){
int ff;
cin>>ff;
unite(f,ff);
}
}
ans=rs[find(0)];
cout<<ans<<endl;
ans=0;
}
}