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
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; }
相关文章推荐
- 【poj 2524】Ubiquitous Religions
- poj 2524 Ubiquitous Religions
- POJ 2524
- POJ-2524-Ubiquitous Religions
- POJ 2524 Ubiquitous Religions(简单并查集)
- POJ 2524 Ubiquitous Religions
- [2524]Ubiquitous Religions (并查集+哈希) (POJ)
- N - Ubiquitous Religions POJ - 2524
- 并查集 poj 1611 2524 1182
- poj 2524(简单dfs(慢了点2000+ms过了))
- POJ 2524 Ubiquitous Religions (并查集)
- POJ 2524 并查集
- POJ 2524 Ubiquitous Religions
- POJ 2524 并查集
- POJ 2524
- poj 2524 Ubiquitous Religions(简单并查集)
- poj 2524 Ubiquitous Religions 并查集问题
- 【POJ 2524 Ubiquitous Religions】+ 并查集
- POJ 2524 Ubiquitous Religions
- POJ 2524 Ubiquitous Religions(并查集)