标签:
Hint Huge input, scanf is recommended.
1 #include<cstdio> 2 int m,n,fa[1010],ans,i,a,b; 3 int find (int x) 4 { 5 int r=x; 6 while(r != fa[r]) 7 { 8 r=fa[r]; 9 } 10 int i=x,j; 11 while(i != r) 12 { 13 j=fa[i]; 14 fa[i]=r; 15 i=j; 16 } 17 return r; 18 } 19 void f1(int x,int y) 20 { 21 int nx,ny; 22 nx=find(x); 23 ny=find(y); 24 if(nx != ny) 25 { 26 fa[ny]=nx; 27 } 28 } 29 int main() 30 { 31 while(scanf("%d",&n) && n) 32 { 33 scanf("%d",&m); 34 for(i = 1 ; i <= n ; i++) 35 { 36 fa[i]=i; //初始化 37 } 38 for(i = 0 ; i < m ; i++) 39 { 40 scanf("%d %d",&a,&b); 41 f1(a,b); //连接ab 42 } 43 int ans=0; 44 for(i = 1 ; i <= n ; i++) 45 { 46 if(fa[i] == i) 47 { 48 ans++; 49 } 50 } 51 printf("%d\n",ans-1); 52 } 53 }
标签:
原文地址:http://www.cnblogs.com/yexiaozi/p/5724843.html