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
For each case, output the number of suspects in one line.
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
并查集是一种树型的数据结构,用于处理一些数据规模庞大的不相交集合(Disjoint Sets)的合并及查询问题。常常在使用中以森林来表示。
N 个不同的元素分布在若干个互不相交集合中,需要进行以下3个操作:
1. 合并两个集合
2. 查询一个元素在哪个集合
3. 查询两个元素是否属于同一集合
并查集由一个整数型的数组和两个函数构成。数组pre[]记录了每个点的前导点(父亲节点)是什么,函数getboot是查找求根,merge是合并两个集合。
合并:merge(a,b)指的是将b所在树的根挂在a所在树的根上。
void merge(int a,int b){//合并为一个集合,将a2所在树的根加到a1所在树的根下
int pa=getboot(a);//获取a1的根节点
int pb=getboot(b);//获取a2的根节点
if(pa==pb)//如果两根节点相同,说明处于一棵树上,就不需要合并了
return;
par[pb]=pa;
total[pa]+=total[pb];//合并之后总结点个数也发生改变,等于原来结点加上新加结点
}
int getboot(),获取根结点并进行状态压缩
最终代码:
#include<iostream>
#include<cstdio>
#define p 30010
using namespace std;
int par[p],total[p];
int n,m;
int k,a,h,h1;
int getboot(int a){//求根
if(par[a]!=a)
par[a]=getboot(par[a]);//路径压缩,查找后使所有结点的父亲结点直接变为根结点,方便查找
return par[a];
}
void merge(int a1,int a2){//合并为一个集合,将a2所在树的根加到a1所在树的根下
int pa=getboot(a1);//获取a1的根节点
int pb=getboot(a2);//获取a2的根节点
if(pa==pb)//如果两根节点相同,说明处于一棵树上,就不需要合并了
return;
par[pb]=pa;
total[pa]+=total[pb];//合并之后总结点个数也发生改变,等于原来结点加上新加结点
}
int main(){
while(true)
{
scanf("%d%d",&n,&m);
if(n==0&&m==0)
break;
for(int i=0;i<n;i++)
{
total[i]=1;
par[i]=i;
}
for(int i=0;i<m;i++)
{
scanf("%d",&k);
scanf("%d",&h);
for(int j=0;j<k-1;j++){
scanf("%d",&h1);
merge(h,h1);
}
}
printf("%d\n",total[getboot(0)]);
}
}
https://blog.csdn.net/liujian20150808/article/details/50848646关于并查集的讲解十分有趣