algorithm_prim

def prim(G):
     dis=0
     x=[1]
     select=G[0]     #edge can be selected next time
     for i in range(len(G)-1):               #add n-1 edge
         for key in select.keys():           #select the next min edge
             if select[key]==min(select.values()):
                 dis+=select[key]
                 x.append(key)               #add the selected node into x[]
                 #update the select{}
                 for keyG in G[key-1]:              
                     if keyG not in x:       #update the already arrivble node
                         if keyG in select.keys():
                             select[keyG]=min(G[key-1][keyG],select[keyG])
                         else:               #add new arrivble node
                             select[keyG]=G[key-1][keyG]
                 del select[key]             #delete the already select edge
     print 'the order is:'
     print x
     return dis
 
 G=[{2:1,3:2},
    {1:1,3:6,4:11},
    {1:2,2:6,4:9,5:13},
    {2:11,3:9,5:7,6:3},
    {3:13,4:7,6:4},
    {4:3,5:4}]
 
 G1=[{2:1,3:6,4:2},
     {1:1,3:7,4:2},
     {1:6,2:7,4:9,5:4,6:3},
     {1:2,2:2,3:9,5:7,6:6},
     {3:4,4:7,6:3},
     {3:3,4:6,5:3}]
 
 print 'the distance is %d'%prim(G)
 print 'the distance is %d'%prim(G1)
 


思路:

做n-1次循环

每次检查可选边字典select{},选最小的加入(初始为1节点的边集)

加入边  的  另一端点  加入x[ ]

更新可选边select{}:

有同样的到达点,取小值(因python字典一键只能一值)

不一样直接加入

删除加入边


建了一个select可选边的字典,比原版的稍有变化。

下次写一个书上的原版的prim算法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值