【POJ-2524】Ubiquitous Religions(并查集)
来源:程序员人生 发布时间:2014-11-27 08:51:32 阅读次数:1896次
并查集。
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 55555;
int fa[maxn];
int vis[maxn];
int n,m,t;
void init(){
for(int i = 0; i < n; i++) {fa[i] = i;}
memset(vis,0,sizeof(vis));
}
int find_father(int u){
return fa[u] == u ? u : fa[u] = find_father(fa[u]);
}
int main(){
int Case = 1;
while(scanf("%d%d",&n,&m)){
if(!m && !n) break;
init();
for(int i = 0; i < m; i++){
int x,y;
scanf("%d%d",&x,&y);
int fx = find_father(x);
int fy = find_father(y);
fa[fx] = fy;
}
int cnt = 0;
for(int i = 1; i <= n; i++){
int t = find_father(i);
if(!vis[t]){
vis[t] = 1;
cnt ++;
}
}
printf("Case %d: %d
",Case++,cnt);
}
return 0;
}
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠