kruskal算法

https://en.wikipedia.org/wiki/Kruskal%27s_algorithm

 1 struct edgetype
 2 {
 3     int from;
 4     int to;
 5     int len;
 6 }edge[100001];
 7 int n,m;
 8 bool com(const edgetype& x,const edgetype& y)
 9 {
10     return x.len<y.len;
11 }
12 int father[10001];
13 int getfather(int x)
14 {
15     if(x==father[x])
16     {
17         return x;
18     }
19     father[x]=getfather(father[x]);
20     return father[x];
21 }
22 bool judge(int x,int y)
23 {
24     return getfather(x)!=getfather(y);
25 }
26 void merge(int x,int y)
27 {
28     x=getfather(x);
29     y=getfather(y);
30     father[x]=y;
31     return;
32 }
33 void init()
34 {
35     scanf("%d%d",&n,&m);
36     for(int i=1;i<=n;i++)
37     {
38         father[i]=i;
39     }
40     for(int i=1;i<=m;i++)
41     {
42         scanf("%d%d%d",&edge[i].from,&edge[i].to,&edge[i].len);
43     }
44     return;
45 }
46 int kruskal()
47 {
48     int res=0;
49     sort(edge+1,edge+1+m,com);
50     for(int i=1;i<=m;i++)
51     {
52         if(judge(edge[i].from,edge[i].to))
53         {
54             res+=edge[i].len;
55             merge(edge[i].from,edge[i].to);
56         }
57     }
58     return res;
59 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值