POJ 1611 The Suspects

题意:说有n个学生,m个小组,然后0号童鞋感染了sars,跟感染者一组的也认为是感染者了,问一共多少感染者。

解法:并查集……

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<math.h>
#include<limits.h>
#include<time.h>
#include<stdlib.h>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#define LL long long
using namespace std;
int father[30005];
int Find(int a)
{
    if(father[a] != a)
        father[a] = Find(father[a]);
    return father[a];
}
void Union(int a, int b)
{
    int c = Find(a), d = Find(b);
    father[c] = d;
}
int main()
{
    int n, m;
    while(~scanf("%d%d", &n, &m) && !(n == 0 && m == 0))
    {
        for(int i = 0; i < n; i++)
            father[i] = i;
        while(m--)
        {
            int k;
            scanf("%d", &k);
            int x;
            if(k--) scanf("%d", &x);
            while(k--)
            {
                int y;
                scanf("%d", &y);
                Union(x, y);
            }
        }
        int root = Find(0);
        int ans = 0;
        for(int i = 0; i < n; i++)
        {
            if(Find(i) == root)
                ans++;
        }
        printf("%d
", ans);
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/Apro/p/4776858.html