标签:
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 65536/32768 K (Java/Others)
1 #include <bits/stdc++.h> 2 using namespace std; 3 int pre[1001],r[1001],t,n,m; 4 int findset(int x) { 5 int r=x; 6 while(pre[r]!=r) r=pre[r]; 7 int i=x,j; 8 while(i!=r) { 9 j=pre[i]; 10 pre[i]=r; 11 i=j; 12 } 13 return r; 14 } 15 void join(int a,int b) { 16 int f1=findset(a),f2=findset(b); 17 if(r[f1]<=r[f2]) { 18 pre[f1]=f2; 19 if(r[f1]==r[f2]) r[f2]++; 20 } 21 else pre[f2]=f1; 22 } 23 int main() { 24 scanf("%d",&t); 25 while(t--) { 26 scanf("%d%d",&n,&m); 27 for (int i=1;i<=n;++i) pre[i]=i,r[i]=1; 28 while(m--) { 29 int a,b; 30 scanf("%d%d",&a,&b); 31 join(a,b); 32 } 33 int cnt=0; 34 for (int i=1;i<=n;++i) if(i==pre[i]) cnt++; 35 printf("%d\n",cnt); 36 } 37 return 0; 38 }
标签:
原文地址:http://www.cnblogs.com/TonyNeal/p/hdu1213.html