hdu 1232 变成生成树至少还要加几条边 (并查集模板题)

求一个图 变成生成树至少还要加几条边(成环的边要删掉,但不用统计)

Sample Input
4 2 //n m
1 3//u v
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0

Sample Output
1
0
2
998

 

 1 # include <iostream>
 2 # include <cstdio>
 3 # include <cstring>
 4 # include <algorithm>
 5 # include <cmath>
 6 # include <queue>
 7 # define LL long long
 8 using namespace std ;
 9 
10 const int MAXN=1010;
11 int F[MAXN];
12 int find(int x)//找x的祖先结点
13 {
14     if(F[x]==x) return x;
15     return F[x]=find(F[x]);
16 }
17 void bing(int u,int v)
18 {
19     int t1=find(u);
20     int t2=find(v);
21     if(t1!=t2)  //这两个点不在一个集合里
22        F[t1]=t2;  //合并到一个集合里
23 }
24 int main()
25 {
26     //freopen("in.txt","r",stdin) ;
27     int n,m;
28     while(scanf("%d",&n),n)
29     {
30         int i ;
31         scanf("%d",&m);
32         for(i=1;i<=n;i++)
33             F[i]=i;
34         int u,v;
35         while(m--)
36         {
37             scanf("%d%d",&u,&v);
38             bing(u,v);
39         }
40         int res=0;
41         for(i=1;i<=n;i++)
42           if(F[i]==i)
43              res++;
44         printf("%d\n",res-1);
45     }
46     return 0;
47 }
View Code

 

posted @ 2015-06-22 23:25  __Meng  阅读(214)  评论(0编辑  收藏  举报