题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1213
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13787 Accepted Submission(s):
6760
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 int father[1010]; 5 6 void set(int n) 7 { 8 for (int i=1; i<=n; i++) 9 father[i]=i; 10 } 11 12 int find(int a) 13 { 14 if (father[a]==a) 15 return a; 16 return father[a]=find(father[a]); 17 } 18 19 void Union(int x,int y) 20 { 21 x=find(x); 22 y=find(y); 23 if (x!=y) 24 father[x]=y; 25 } 26 27 int main () 28 { 29 int t,k; 30 while (cin>>t) 31 { 32 33 while (t--) 34 { 35 k=0; 36 int n,m; 37 cin>>n>>m; 38 set(n); 39 while (m--) 40 { 41 int s,d; 42 cin>>s>>d; 43 Union(s,d); 44 } 45 for (int i=1; i<=n; i++) 46 { 47 if (father[i]==i) 48 k++; 49 } 50 printf ("%d\n",k); 51 } 52 } 53 return 0; 54 }
hdu 1213 How Many Tables(并查集算法)
原文:http://www.cnblogs.com/qq-star/p/3937371.html