【解题报告】【HDOJ1213】【并查集】How Many Tables

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1213

 1 #include<stdio.h>
 2 #include<string.h>
 3 int father[1005];
 4 int record[1005];
 5 int find(int x)
 6 {
 7     int t;
 8     if(father[x]==x)
 9         return x;
10     t=find(father[x]);
11     father[x]=t;
12     return t;
13 }
14 int main()
15 {
16     int t,n,m,a,b,i,fx,fy,sum;
17     //freopen("1.txt","r",stdin);
18     scanf("%d",&t);
19     while(t--)
20     {
21         scanf("%d%d",&n,&m);
22         for(i=1;i<=n;i++)
23         {
24             father[i]=i;
25             record[i]=0;
26         }
27         for(i=0;i<m;i++)
28         {
29             scanf("%d%d",&a,&b);
30             fx=find(a);
31             fy=find(b);
32             father[fx]=fy;
33         }
34         
35         for(i=1;i<=n;i++) 
36         {
37             father[i]=find(father[i]);
38             record[father[i]]=1;
39         }
40         sum=0;
41         for(i=1;i<=n;i++)
42             if(record[i]) sum++;
43             printf("%d\n",sum);
44             getchar();
45     }
46     return 0;
47 }

 

posted on 2012-07-21 16:45  coding封神  阅读(122)  评论(0编辑  收藏  举报

导航