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