您的位置:首页 > 理论基础 > 数据结构算法

poj 2524 Ubiquitous Religions(数据结构:并查集)

2014-07-22 16:50 513 查看
题意是告诉你有n个学生,其中m对学生信仰相同

让你输出n个学生一共有多少个信仰

简单并查集的使用,学生信仰相同则并入相同集合

最后输出有多少个集合即可

注意数组大小,因为这个RE了一次


代码如下:

#include <cstdio>
#include <iostream>
#include <algorithm>
#define MAXN 50010
#define LL long long
using namespace std;

int p[MAXN], n, m;

int find(int x) {
return p[x]==x ? x : p[x] = find(p[x]);
}

int cnt() {
int i, ans = 0;
for(i=0; i<n; ++i) {
if(p[i] == i)
ans++;
}
return ans;
}

int main(void) {
int a, b, i, res = 1;
while(scanf("%d%d", &n, &m) && (n+m)) {
for(i=1; i<=n; ++i)
p[i] = i;
while(m--) {
scanf("%d%d", &a, &b);
a = find(a);
b = find(b);
if(a != b)
p[a] = b;
}
printf("Case %d: %d\n", res++, cnt());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: