您的位置:首页 > 其它

POJ2524 并查集

2017-05-29 13:29 218 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息