(使用树结构来支持并查集操作8.4.4)POJ 2524 Ubiquitous Religions(并查集的基本操作: 求有多少个相互独立的集合)

来源:互联网 发布:日本科研实力知乎 编辑:程序博客网 时间:2024/05/18 01:48
/* * POJ_2524.cpp * *  Created on: 2013年11月6日 *      Author: Administrator */#include <iostream>#include <cstdio>using namespace std;const int maxn = 50010;int father[maxn];int find(int x){//并查集的查询if(father[x] == x){return x;}return (father[x] = find(father[x]));}void join(int x,int y){//并查集的合并x = find(x);y = find(y);if(x != y){father[x] = y;}}int main(){int n,m;int counter = 1;while(scanf("%d%d",&n,&m)!=EOF,n||m){int x,y;int i;for(i = 1 ; i <= n  ; ++i){father[i] = i;}for(i = 1 ; i <= m ; ++i){scanf("%d%d",&x,&y);join(x,y);}int cnt = 0;for(i = 1 ; i <= n ; ++i){//就算有多少个相互独立的集合if(father[i] == i){cnt++;}}printf("Case %d: %d\n",counter++,cnt);}return 0;}