poj 1611-The Suspects(并查集)

本文探讨了使用并查集算法解决SARS疫情中有效隔离感染和接触者的问题,通过分析疫情传播特点,设计算法模型,实现对潜在感染者的精准定位,确保公共卫生安全。
题目大意:
SARS(非典型肺炎)传播得非常厉害,其中最有效的办法是隔离那些患病、和患病者接触的人。现在有几个学习小组,每小组有几个学生,一个学生可能会参加多个小组。
小组中只要有一个人得病,其余的都是嫌疑人。现在已知这些小组的人员,且0号学生已经患病,求一共有多少个嫌疑人。

解析:

并查集的水题,套并查集的模板,并计算出与0号,所在同一个集合的有多少人就好了。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 30010;
int pa[N],son[N];
int n, m;
void init() {
	for(int i = 0; i < n; i++) {
		pa[i] = i;
		son[i] = 1;
	}
}
int getPa(int x) {
	if(x == pa[x]) {
		return x;
	}else {
		return x = getPa(pa[x]);
	}
}
void Union(int x1,int x2) {
	int root1 = getPa(x1) ,root2 = getPa(x2);
	if(root1 == root2) {
		return ;
	}
	if(root1 < root2) {
		pa[root2] = root1;
		son[root1] += son[root2];
	}else {
		pa[root1] = root2;
		son[root2] += son[root1];
	}
}
int main() {
	int num, first,next;
	while(scanf("%d%d",&n,&m) != EOF && (m || n)) {
		init();
		for(int i = 0; i < m; i++) {
			scanf("%d",&num);
			scanf("%d",&first);
			for(int j = 1; j < num; j++) {
				scanf("%d",&next);
				Union(first,next);
			}
		}
		printf("%d\n",son[0]);
	}
	return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值