POJ2524 并查集

2017年3月18日 | ljfcnyali
题目大意
世界上宗教何其多。假设你对自己学校的学生总共有多少种宗教信仰很感兴趣。学校有n个学生,但是你不能直接问学生的信仰,不然他会感到很不舒服的。有另外一个方法是问m对同学,是否信仰同一宗教。根据这些数据,相信聪明的你是能够计算学校最多有多少种宗教信仰的。

Sample Input

10 9
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
10 4
2 3
4 5
4 8
5 8
0 0

Sample Output

Case 1: 1
Case 2: 7

题目分析
显然一个并查集,然后先按照题目要求乱搞,然后搞完后就一个个枚举,看看有没有自己等于自己爸爸的,那个人就是一个独立的宗教信仰里的老大。

AC代码

/*************************************************************************
    > File Name: POJ2524.cpp
    > Author: ljf-cnyali
    > Mail: ljfcnyali@gmail.com 
    > Created Time: 2017/3/18 14:02:16
 ************************************************************************/

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
#include<vector>
#include<queue>

using namespace std;

#define REP(i, a, b) for(int i = (a), _end_ = (b);i <= _end_; ++ i)
#define mem(a) memset((a), 0, sizeof(a))
#define str(a) strlen(a)

const int maxn = 50010;

int n, m, ans;

int f[maxn], rank[maxn];

int cha(int x) {
    return x == f[x] ? x : f[x] = cha(f[x]);
}

void union_set(int x, int y) {
    int fx = cha(x), fy = cha(y);
    if(fx != fy) {
        if(rank[fx] >= rank[fy]) {
            f[fy] = fx;
            rank[fx] += rank[fy];
        }
        else {
            f[fx] = fy;
            rank[fy] += rank[fx];
        }
    }
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    int k = 0;
    while(1) {
        scanf("%d%d", &n, &m);
        if(n + m == 0)
            return 0;
        mem(rank);
        REP(i, 1, n)
            f[i] = i;
        int x, y;
        ans = 0;
        REP(i, 1, m) {
            scanf("%d%d", &x, &y);
            union_set(x, y);
        }
        REP(i, 1, n)
            if(i == f[i])
                ++ ans;
        printf("Case %d: %d\n", ++ k, ans);
    }
    return 0;
}

本文转自:http://ljf-cnyali.cn/index.php/archives/69

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值