hdu1233

http://acm.hdu.edu.cn/showproblem.php?pid=1233

最小生成树,kruskal算法

 1 #include<stdio.h>
 2 #include<math.h>
 3 #include<string.h>
 4 #include<stdlib.h>
 5 #include<iostream>
 6 using namespace std;
 7 const int N=5005;
 8 struct stu{
 9     int u;
10     int v;
11     int w;
12 }p[N];
13 int n,m;
14 int father[N];
15 
16 int cmp(const void *a,const void *b)
17 {
18     return (*(struct stu*)a).w > (*(struct stu*)b).w?1:-1;
19 }
20 int find(int x)
21 {
22     if(father[x]!=x)
23     father[x]=find(father[x]);
24     return father[x];
25 }
26 int make(int a,int b)
27 {
28     int f1=find(a);
29     int f2=find(b);
30     if(f1!=f2)
31     {
32         father[f2]=f1;
33         return 1;
34     }
35     return 0;
36 }
37 int kruskal()
38 {
39     int cns=0,k=0;
40     for(int i=0;i<m;i++)
41     {
42         if(make(p[i].u,p[i].v))
43         {
44             cns+=p[i].w;
45             k++;
46         }
47         if(k==n-1)
48         return cns;
49     }
50     return cns;
51 }
52 
53 int main()
54 {
55     while(~scanf("%d",&n))
56     {
57         if(!n)
58         break;
59         m=n*(n-1)/2;
60         for(int i=1;i<=n;i++)
61         father[i]=i;
62         for(int i=0;i<m;i++)
63         {
64             scanf("%d%d%d",&p[i].u,&p[i].v,&p[i].w);
65         }
66         qsort(p,m,sizeof(struct stu),cmp);
67         printf("%d\n",kruskal());
68 
69     }
70     return 0;
71 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值