标签:
求一个图 变成生成树至少还要加几条边(成环的边要删掉,但不用统计)
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 }
hdu 1232 变成生成树至少还要加几条边 (并查集模板题)
标签:
原文地址:http://www.cnblogs.com/-Buff-/p/4594227.html