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()

你可能感兴趣的:(python,开发语言,算法)