您的位置:首页 > 产品设计 > UI/UE

POJ 2524 - Ubiquitous Religions

2012-10-09 20:53 288 查看
Advanced Data Structures :: Disjoint Set

Description

有n个学生,编号从1~n。

学生们大都信仰着各自的神,各自的宗教。

当然也有不少同学有着相同的信仰。

那么,告诉你哪些同学有相同的信仰,

请求出有多少个神在同学们的心中。

Type

Advanced Data Structures :: Disjoint Set

Analysis

假设一个开头就有n个宗教,

然后用并查集并一下,

在并的时候检查是否原来就在同一个宗教,

否则每次合并都会少一个宗教。

并完之后,剩下的宗教数就是最后要求的宗教数了。

Solution

// POJ 2524
// Ubiquitous Religions
// by A Cod e Rabbit

#include <cstdio>

const int MAXN = 50002;

struct DisjointSet {
int p[MAXN];
int ans;
void Init(int);
void Make(int x) { p[x] = x; }
int Find(int x) { return p[x] == x ? x : p[x] = Find(p[x]); }
int Union(int x, int y) {
if (Find(x) != Find(y)) ans--;
p[Find(x)] = Find(y);
}
};

void DisjointSet::Init(int n) {
for (int i = 1; i <= n; i++)
Make(i);
ans = n;
}

int n, m;
DisjointSet set;

int main() {
int cnt_case = 0;
while (scanf("%d%d", &n, &m) && (n || m)) {
set.Init(n);
for (int i = 0; i < m; i++) {
int x, y;
scanf("%d%d", &x, &y);
set.Union(x, y);
}
printf("Case %d: %d\n", ++cnt_case, set.ans);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: