poj 1611-The Suspects(并查集)

来源:互联网 发布:天涯和知乎哪个实用 编辑:程序博客网 时间:2024/05/17 00:54
题目大意:
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;}

0 0