1 //直接并查集 2 #include<cstdio> 3 #include<cstdlib> 4 #include<cstring> 5 #include<algorithm> 6 #include<iostream> 7 using namespace std; 8 int n,m; 9 int fa[505000]; 10 int find(int x){ 11 return fa[x]==x?fa[x]:fa[x]=find(fa[x]); 12 } 13 int join(int x,int y){ 14 int fx=find(x), 15 fy=find(y); 16 if(fx!=fy)fa[fx]=fy; 17 } 18 int main() 19 { 20 int n,m,cnt=1; 21 while(scanf("%d%d",&n,&m)==2&&n&&m){ 22 for(int i=1;i<=n;i++) fa[i]=i; 23 while(m--){ 24 int a,b; 25 scanf("%d%d",&a,&b); 26 join(a,b); 27 } 28 int sum=0; 29 for(int i=1;i<=n;i++) 30 if(fa[i]==i) sum++; 31 printf("Case %d: %d\n",cnt,sum); 32 cnt++; 33 } 34 return 0; 35 }
原文:http://www.cnblogs.com/shenben/p/5459886.html