hdu 1213 How Many Tables

http://acm.hdu.edu.cn/showproblem.php?pid=1213   并查集

View Code
 1 #include<iostream>
2 #include<algorithm>
3 #include<climits>
4 #include<cstdio>
5 using namespace std;
6 int father[1008];
7 int t,n,m;
8 void init(int n)
9 {
10 for(int i=0;i<=n;i++) father[i]=i;
11 }
12 int find(int x)
13 {
14 int i=x,temp;
15 while(i!=father[i]) i=father[i];
16 while(x!=i)
17 {
18 temp=father[x];
19 father[x]=i;
20 x=temp;
21 }
22 return i;
23 }
24 int main()
25 {
26 scanf("%d",&t);
27 while(t--)
28 {
29 int x,y,fatherx,fathery;
30 scanf("%d%d",&n,&m);
31 init(n);
32 while(m--)
33 {
34 scanf("%d%d",&x,&y);
35 fatherx=find(x);
36 fathery=find(y);
37 //cout<<fatherx<<" "<<fathery<<endl;
38 if(fatherx!=fathery)
39 {
40 father[fatherx]=fathery;
41 n--;///记录集合个数、
42 }
43 }
44 printf("%d\n",n);
45 }
46 return 0;
47 }


 

posted @ 2012-03-29 11:20  keepmoving89  阅读(156)  评论(0编辑  收藏  举报