POJ 1611 The Suspects (并查集)

The Suspects

题目链接:

http://acm.hust.edu.cn/vjudge/contest/123393#problem/B

Description

严重急性呼吸系统综合症( SARS), 一种原因不明的非典型性肺炎,从2003年3月中旬开始被认为是全球威胁。为了减少传播给别人的机会, 最好的策略是隔离可能的患者。
在Not-Spreading-Your-Sickness大学( NSYSU), 有许多学生团体。同一组的学生经常彼此相通,一个学生可以同时加入几个小组。为了防止非典的传播,NSYSU收集了所有学生团体的成员名单。他们的标准操作程序(SOP)如下:
一旦一组中有一个可能的患者, 组内的所有成员就都是可能的患者。
然而,他们发现当一个学生被确认为可能的患者后不容易识别所有可能的患者。你的工作是编写一个程序, 发现所有可能的患者。

Input

输入文件包含多组数据。
对于每组测试数据:
第一行为两个整数n和m, 其中n是学生的数量, m是团体的数量。0 < n <= 30000,0 <= m <= 500。
每个学生编号是一个0到n-1之间的整数,一开始只有0号学生被视为可能的患者。
紧随其后的是团体的成员列表,每组一行。
每一行有一个整数k,代表成员数量。之后,有k个整数代表这个群体的学生。一行中的所有整数由至少一个空格隔开。
n = m = 0表示输入结束,不需要处理。

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

题意:

有n个学生,分成m个小组;
若有学生可能感染SARS,则其所在的小组均被视为可能的患者.
一开始只有学生#0染病;
输出所有可能的患者的数量.

题解:

很明显的并查集模版题.
将同一小组的所有人合并到一起;
查询每个学生是否跟#0在一个集合.

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <vector>
#define LL long long
#define eps 1e-8
#define maxn 31000
#define inf 0x3f3f3f3f
#define IN freopen("in.txt","r",stdin);
using namespace std;

int fa[maxn];
int rank[maxn];

void init_set() {
    for(int i=0; i<maxn; i++) {
        fa[i] = i;
        rank[i] = 0;
    }
}

int find_set(int x) {
    return fa[x] = (x==fa[x]? x:find_set(fa[x]));
}

void unit_set(int x, int y) {
    x = find_set(x);
    y = find_set(y);
    if(rank[x] < rank[y]) swap(x, y);
    fa[y] = x;
    if(rank[x] == rank[y]) rank[x]++;
}

int n, m;

int main(int argc, char const *argv[])
{
    //IN;

    while(scanf("%d %d", &n,&m) != EOF && (m||n))
    {
        init_set();
        while(m--) {
            int k; scanf("%d", &k);
            if(!k) continue;
            int x; scanf("%d", &x); k--;
            while(k--) {
                int y; scanf("%d", &y);
                unit_set(x, y);
            }
        }

        int cnt = 0;
        for(int i=0; i<n; i++) {
            if(find_set(i) == find_set(0)) cnt++;
        }

        printf("%d\n", cnt);
    }

    return 0;
}

posted @ 2016-07-23 16:47  Sunshine_tcf  阅读(205)  评论(0编辑  收藏  举报