程序员人生 网站导航

【POJ-2524】Ubiquitous Religions(并查集)

栏目:互联网时间:2014-11-27 08:51:32

并查集。

#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; }

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐