标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 37637 Accepted Submission(s):
19911
1 #include<stdio.h> 2 #include<algorithm> 3 using namespace std; 4 int n,per[1000]; 5 void init() 6 { 7 int i; 8 for(i=1;i<=n;i++) 9 per[i]=i;//初始化数组 10 } 11 12 int find(int x)//查找函数,找到x的根节点 13 { 14 int t=x; 15 while(t!=per[t])//压缩路径 16 t=per[t]; 17 per[x]=t; 18 return t; 19 } 20 void join(int x,int y) 21 { 22 int fx=find(x); 23 int fy=find(y); 24 if(fx!=fy) 25 per[fx]=fy; 26 } 27 int main() 28 { 29 int a,b,c; 30 while(scanf("%d%d",&n,&b),n) 31 { 32 int i,s,d,cot=0; 33 init(); 34 for(i=0;i<b;i++) 35 { 36 scanf("%d %d",&s,&d); 37 //per[s]=d; 38 join(s,d); 39 } 40 for(i=1;i<=n;i++) 41 { 42 if(per[i]==i) 43 //if(find(i)==i) 44 cot++;//找根节点的个数 45 } 46 printf("%d\n",cot-1); 47 } 48 return 0; 49 }
标签:
原文地址:http://www.cnblogs.com/Eric-keke/p/4687331.html