POJ1611-The Suspects 【并查集】

The Suspects

题意

在一个学校,一共有N个学生,他们组建了M个小组,现在有一个人中了病毒,具有传染性,与感染者同组人员都会被传染,问最终会传染多少人?

分析

使用并查集,把有联系的人都合并起来,最后压缩一边路径,看其id号为0的点有多少个就可以了

AC 代码

#include <iostream>
#include <stdio.h>
using namespace std;
typedef long long ll;
const int maxn = 3e4+10;

int N,M;
int fa[maxn];
int arr[maxn];
void init(){
    for(int i = 0;i<N;i++) fa[i] = i;
}
int find(int x){
    if(x != fa[x])
        fa[x] = find(fa[x]);
    return fa[x];
}
void join(int x,int y){
    int fx = find(x),fy = find(y);
    if(fx != fy){
        if(fx == 0) fa[fy] = fx;
        else fa[fx] = fy;
    }
}
int main(){
    while(scanf("%d %d",&N,&M)){
        if(N == 0 && M == 0) break;
        init();
        while (M--){
            int k;
            scanf("%d",&k);
            for(int i = 0;i<k;i++) {
                scanf("%d",&arr[i]);
                if(i) join(arr[i-1],arr[i]);
            }
        }
        for(int i = 0;i<N;i++) find(i);//把所有的路径都压缩一下
        int res = 0;
        for(int i = 0;i<N;i++)
            if(fa[i] == 0){
                res++;
            }
        printf("%d\n",res);
    }

    return 0;
}
全部评论

相关推荐

06-27 18:45
中山大学 Ruby
25届应届毕业生,来广州2个礼拜了,找不到工作,绝望了,太难过了…
应届想染班味:9爷找不到工作只能说明,太摆了或者太挑了。
点赞 评论 收藏
分享
06-12 16:23
已编辑
小米_软件开发(准入职员工)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务