POJ1611The Suspects

一.原题链接:http://poj.org/problem?id=1611

二.题意:0号是病人,跟病人一个小组可能会被感染,求被可能感染人数。

三.代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>

using namespace std;

const int INF = 1<<29;

int pre[30050];
int member[30005];

int findRoot(int x)
{
    int root = pre[x], child, save;
    while(root != pre[root])
        root = pre[root];

//路径压缩
    child = x;
    while(pre[child] != root){
        save = pre[child];
        pre[child] = root;
        child = save;
    }

    return root;
}

void jion(int father, int child)
{
    int RootFather = findRoot(father),
        RootChild = findRoot(child);


    if(RootFather != RootChild){
        pre[RootChild] = RootFather;
    }
}

int main()
{
    //freopen("in.txt", "r", stdin);
    int numOfStudent, numOfGroup,
        i, j, perMem, zeroRoot, ans;

    while(1){
        cin>>numOfStudent>>numOfGroup;
        if(!numOfStudent && !numOfGroup)
            break;

        for(i = 0; i < numOfStudent; i++)
            pre[i] = i;

        for(i = 0; i < numOfGroup; i++){
            scanf("%d", &perMem);
            for(j = 0; j < perMem; j++){
                scanf("%d", &member[j]);
            }
            for(j = 1; j <perMem; j++){
                jion(member[0], member[j]);
            }
        }

        ans = 0;
        zeroRoot = findRoot(0);
        for(i = 0; i < numOfStudent; i++)
            if(zeroRoot == findRoot(i))
                ans++;

        cout<<ans<<endl;
    }

    return 0;
}


你可能感兴趣的:(POJ1611The Suspects)