码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-06-23 00:48:22      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

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

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)
13 {
14     if(F[x]==-1) 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) F[t1]=t2;
22 }
23 int main()
24 {
25     //freopen("in.txt","r",stdin) ;
26     int n,m;
27     while(scanf("%d",&n),n)
28     {
29         int i ;
30         scanf("%d",&m);
31         for(i=1;i<=n;i++)
32             F[i]=-1;
33         int u,v;
34         while(m--)
35         {
36             scanf("%d%d",&u,&v);
37             bing(u,v);
38         }
39         int res=0;
40         for(i=1;i<=n;i++)
41           if(F[i]==-1)
42              res++;
43         printf("%d\n",res-1);
44     }
45     return 0;
46 }
View Code

 

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

标签:

原文地址:http://www.cnblogs.com/-Buff-/p/4594227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!