day59-graph theory-part09-8.30

tasks for today:

1. digkstra 堆优化版 47.参加科学大会

2. bellman_ford算法 94.城市间货物运输I

---------------------------------------------------------------------------------

1. dijkstra 堆优化版

This is an optimization for the vanilla dijkstra, through using a heap to simplify the process of finding curNode in each round of updating, which also in turn simplifies the process of updating of minDis list in each round. Besides, using a adjcent list to replace the adjcent table.

import heapq

class Edge:
    def __init__(self, to, val):
        self.to = to
        self.val = val

def main():
    n, m = map(int, input().split())
    
    grid = [[] for _ in range(n+1)]
    
    for _ in range(m):
        s, e, v  = map(int, input().split())
        grid[s].append(Edge(e, v))
        
    visited = [False] * (n+1)
    minDis = [float('inf')] * (n+1)
    
    start = 1
    end = n
    
    curHQ = []
    
    heapq.heappush(curHQ, (0, start))
    
    minDis[start] = 0
    
    while curHQ:
        curDis, curNode = heapq.heappop(curHQ)
        
        if visited[curNode]: continue
        
        visited[curNode] = True
        
        for edge in grid[curNode]:
            if not visited[edge.to] and minDis[curNode] + edge.val < minDis[edge.to]:
                minDis[edge.to] = minDis[curNode] + edge.val
                heapq.heappush(curHQ, (minDis[edge.to], edge.to))
    
    if minDis[n] == float('inf'): 
        print(-1)
    else:
        print(minDis[n])
        
    return

if __name__ == "__main__":
    main()

2. bellman_ford算法 94.城市间货物运输I

In this practice, the edge weight can be negative, which is not suitable being solved by the dijkstra method, choose bellman-ford method.

start=1 end=n, do n-1 times' relaxation to find the min distance from starting point to all the other points.

def main():
    n, m = map(int, input().split())
    
    grid = []
    
    for _ in range(m):
        s, t, v = map(int, input().split())
        grid.append([s, t, v])
    
    minDis = [float('inf')] * (n+1)
    
    start = 1
    end = n
    
    minDis[start] = 0
    
    for _ in range(n-1):
        update = False
        for edge in grid:
            fromNode = edge[0]
            toNode = edge[1]
            weight = edge[2]
            if minDis[fromNode] != float('inf') and minDis[toNode] > minDis[fromNode] + weight:
                minDis[toNode] = minDis[fromNode] + weight
                update = True
        if not update:
            break
    
    if minDis[end] == float('inf'):
        print('unconnected')
    else:
        print(minDis[end])
    
    return


if __name__ == "__main__":
    main()
  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值