题意:N个学生分属M个团体,(0<N<=30000,0<=M<=500)一个学生可以属于多个团体。如果一个学生疑似患病,则它所属的整个团体都疑是患病。已知0号学生疑是患病,以及每个团体都有哪些学生构成,求一共多少个学生疑是患病。
Input
The input file contains several cases. Each test case begins with two integers n and m in a line, where n is the number of students, and m is the number of groups. You may assume that 0 < n <= 30000 and 0 <= m <= 500. Every student is numbered by a unique integer between 0 and n−1, and initially student 0 is recognized as a suspect in all the cases. This line is followed by m member lists of the groups, one line per group. Each line begins with an integer k by itself representing the number of members in the group. Following the number of members, there are k integers representing the students in this group. All the integers in a line are separated by at least one space. A case with n = 0 and m = 0 indicates the end of the input, and need not be processed.
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
**思路:**对于每一个团体把他们加入一个集合中,同时记录集合中学生的个数,最后只需要找到,0号学生所在的学生集合中的人数即可,思路简单,只需要在标准并查集的基础上加入一个数组numbers[],numbers[i]初始化为1, n u m b e r s [ f i n d _ r o o t ( i ) ] numbers[ find\_root(i) ] numbers[find_root(i)]表示第i号学生所属的集合中的人数(只维护树的根节点的numbers数组的值),只需要在union函数中合并时,假设该集合的根节点为root,只需要更新numbers[root]即可,最后先找到0号学生所在集合的根节点root0=find_root(0),然后输出numbers[root0]即可。
代码
#include "iostream"
using namespace std;
int N, M;
int parent[30000];
int numbers[30000];
int find_root(int x){
if(parent[x] == x)
return x;
else{
return parent[x] = find_root(parent[x]);
}
}
void union_tree(int x, int y){
int x_root = find_root(x);
int y_root = find_root(y);
if(x_root == y_root){
return;
}
else{
parent[x_root] = y_root;
numbers[y_root] += numbers[x_root];
}
}
int main(){
while(1){
for (int i = 0; i < 30000;i++){
parent[i] = i;
numbers[i] = 1;
}
cin >> N >> M;
if(N==0&&M==0)
break;
for (int m = 0; m < M;m++){
int k;
cin >> k;
int u;
cin >> u;
for (int i = 1; i < k; i++)
{
int v;
cin >> v;
union_tree(u, v);
}
}
int root0 = find_root(0);
cout << numbers[root0] << endl;
}
//system("pause");
return 0;
}