POJ2524 Ubiquitous Religions(并查集)

时间:2023-12-27 14:17:13

题目链接

分析:

给定 n 个点和 m 条无项边,求连通分量的数量。用并查集很简单。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <map>
#include <queue>
#include <cmath> using namespace std; const int maxn = + ; int p[maxn]; int find(int x) { return x == p[x] ? x : (p[x] = find(p[x])); } int main(){
int n, m, a, b, kase = ; while(scanf("%d%d", &n, &m) == ) {
if(n == && m == ) break;
for(int i=; i<=n; i++) p[i] = i; int cnt = ; for(int i=; i<m; i++) {
scanf("%d %d", &a, &b); int x = find(a), y = find(b);
if(x != y) {
p[x] = y;
}
} for(int i=; i<=n; i++) {
if(p[i] == i) cnt++;
} printf("Case %d: ", ++kase);
printf("%d\n", cnt);
} return ;
}