poj2524 Ubiquitous Religions(并查集)
2017-11-30 22:18
621 查看
题目链接
http://poj.org/problem?id=2524
题意
有n个学生,编号1~n,每个学生最多有1个宗教信仰,输入m组数据,每组数据包含a、b,表示同学a和同学b有相同的信仰,求在n名学生中最多存在多少种不同的宗教信仰。
思路
使用并查集解决。
代码
#include <iostream> #include <cstring> #include <cstdio> using namespace std; const int N = 50000 + 10; int p ; void make_set(int n) { for (int i = 1;i <= n;i++) p[i] = -1; } int find_root(int i) { if (p[i] == -1) return i; else { int temp = find_root(p[i]); //路径压缩 p[i] = temp; return temp; } } void union_set(int a, int b) { int ra = find_root(a); int rb = find_root(b); if (ra != rb) p[ra] = rb; } int main() { //freopen("poj2524.txt", "r", stdin); int n, m; int cnt = 0; while (scanf("%d%d", &n, &m) == 2 && n) { make_set(n); int a, b; for (int i = 0; i < m; i++) { scanf("%d%d", &a, &b); union_set(a, b); } int ans = 0; for (int i = 1;i <= n;i++) if (p[i] == -1) ans++; printf("Case %d: %d\n", ++cnt, ans); } return 0; }
相关文章推荐
- POJ 2524 Ubiquitous Religions (带权并查集)
- POJ2524——宗教(Ubiquitous Religions)【图论,并查集】
- poj 2524 Ubiquitous Religions(并查集)
- POJ 2524 Ubiquitous Religions (并查集)
- POJ 2524 并查集
- POJ - 2524 - Ubiquitous Religions(并查集)
- poj 2524 Ubiquitous Religions [并查集]
- poj 2524-Ubiquitous Religions(并查集)
- poj 2524:Ubiquitous Religions(并查集,入门题)
- Ubiquitous Religions POJ - 2524(并查集)
- poj并查集问题-2524
- poj 2524宗教信仰 并查集水题
- POJ2524 并查集水题
- poj 2524 Ubiquitous Religions 并查集
- (使用树结构来支持并查集操作8.4.4)POJ 2524 Ubiquitous Religions(并查集的基本操作: 求有多少个相互独立的集合)
- POJ2524 Ubiquitous Religions(并查集)
- POJ - 2524 Ubiquitous Religions(简单并查集)
- POJ---2524 Ubiquitous Religions【并查集】
- POJ 2524-Ubiquitous Religions 并查集
- POJ 2524 并查集