标签:
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 30791 | Accepted: 14928 |
Description
Input
Output
Sample Input
10 9 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 10 4 2 3 4 5 4 8 5 8 0 0
Sample Output
Case 1: 1 Case 2: 7
Hint
Source
#include <iostream> #include <cstring> using namespace std; const int maxn=50000+10; int fa[maxn]; int Find(int x) { if(fa[x]==-1) return x; return fa[x]=Find(fa[x]); } int Bind(int x,int y) { int fx=Find(x); int fy=Find(y); if(fx!=fy) { fa[fx]=fy; return 1; } return 0; } int main() { int n,m,x,y; int kase=0; while(cin>>n>>m,n,m) { int ans=n; memset(fa,-1,sizeof(fa)); while(m--) { cin>>x>>y; ans-=Bind(x,y); } cout<<"Case "<<++kase<<": "<<ans<<endl; } }
#include <iostream> #include <cstring> using namespace std; const int maxn =50000+5; int fa[maxn]; int Find(int x) { if(fa[x]==-1) return x; return fa[x]=Find(fa[x]); } void Bind(int x,int y) { int fx=Find(x); int fy=Find(y); if(fx!=fy) fa[fx]=fy; } int main() { int n,m,x,y; int kase=0; while(cin>>n>>m,n,m) { memset(fa,-1,sizeof(fa)); while(m--) { cin>>x>>y; Bind(x,y); } int ans=0; for(int i=1;i<=n;i++) if(fa[i]==-1) ans++; cout<<"Case "<<++kase<<": "<<ans<<endl; } return 0; }
#include <iostream> #include <cstring> using namespace std; const int maxn =50000+5; int fa[maxn]; int Find(int x) { if(fa[x]==x) return x; return fa[x]=Find(fa[x]); } void Bind(int x,int y) { int fx=Find(x); int fy=Find(y); if(fx!=fy) fa[fx]=fy; return; } int main() { int n,m,x,y; int kase=0; while(cin>>n>>m,n,m) { for(int i=1;i<=n;i++) fa[i]=i; while(m--) { cin>>x>>y; Bind(x,y); } int ans=0; for(int i=1;i<=n;i++) { int t=Find(i); if(fa[i]==i) ans++; } cout<<"Case "<<++kase<<": "<<ans<<endl; } }
POJ 2524 Ubiquitous Religions (简单并查集,三种方式)
标签:
原文地址:http://blog.csdn.net/hurmishine/article/details/51628817