Wek6 B - Union checking set

问题描述:

新型冠状病毒肺炎(Corona Virus Disease 2019,COVID-19),简称“新冠肺炎”,是指2019新型冠状病毒感染导致的肺炎。
如果一个感染者走入一个群体,那么这个群体需要被隔离!
小A同学被确诊为新冠感染,并且没有戴口罩!!!!!!
危!!!
时间紧迫!!!!
需要尽快找到所有和小A同学直接或者间接接触过的同学,将他们隔离,防止更大范围的扩散。
众所周知,学生的交际可能是分小团体的,一位学生可能同时参与多个小团体内。
请你编写程序解决!戴口罩!!

解题思路:

这是典型的并查集题,最后输出小A同学所在类的成员数即可。并查集思想:初始化每个成员的根节点都是自己,最后在题目的要求下合并类,合并时:如果a,b各自的类为rootA,rootB,如果rootA!=rootB,则root[rootB]=rootA,这样b所在类就挂在了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

实验代码:

#include<iostream>
using namespace std;
int maxn=30020;
int root[30020];			 
int rnk[30020];			//维护每个类的大小
int stu[30020];			 
void unit(int n)		
{
	for(int i=0;i<n;i++)		
	{
		root[i]=i;
		rnk[i]=1;			
	}
}
int find(int a)		
{
	if(root[a]==a)		 
		return a;
	else
		return find(root[a]);	
}
bool unit(int a,int b)			
{
	int rootA=find(a);		
	int rootB=find(b);		
	if(rootA==rootB)
		return false;		
	else
	{
		root[rootB]=rootA;					
		rnk[rootA]+=rnk[rootB];				
		return true;
	} 
} 
void biaoqi(int num)
{
	int mofan=find(stu[0]);
	int clas;
	for(int i=1;i<num;i++)
	{
		clas=find(stu[i]);
		if(mofan!=clas)
		{
			root[clas]=mofan;
			rnk[mofan]+=rnk[clas];
		}
	}
} 
int main(void)
{
	int n,m,num;		
	while(cin>>n>>m)		
	{
		if(n==0&&m==0)
			return 0;
		unit(n); 		
		for(int i=0;i<m;i++)		
		{
			cin>>num;			
			for(int j=0;j<num;j++)
				cin>>stu[j];				
			for(int j=1;j<num;j++)
				unit(stu[j-1],stu[j]);			
		} 
		cout<<rnk[ find(0) ]<<endl;
	}
	return 0;
 } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值