代码随想录算法训练营第58天|dijkstra(堆优化)、Bellman_ford 算法(可以处理带负权重的边)

dijkstra(堆优化)

卡码网 47. 参加科学大会
代码随想录

import heapq

V, E = map(int, input().split())

graph = {}
for _ in range(E):
    s,t,val = map(int, input().split())
    if s not in graph:
        graph[s] = []
        
    graph[s].append((t,val))

# print(graph)

visited = [False] * (V+1)

# 创建最小堆,并初始化
distance_queue = []
heapq.heappush(distance_queue, (0,1))
# for i in range(2, V + 1):
#     heapq.heappush(distance_queue, (float("+inf"),i))

# 存放最后的结果
distance = [float("+inf")] * (V + 1)

# 开始弹出元素
while distance_queue:
    # print(distance_queue)
    v, s = heapq.heappop(distance_queue)
    
    if visited[s]:
        continue
    # distance[s] = min(v, distance[s])
    visited[s] = True
    neighbor_nodes = graph.get(s,None)
    if not neighbor_nodes:
        continue
    for neighbor_u, neighbor_v in neighbor_nodes:
        # if neighbor_u not in visited: 这里又错了。和之前 赋值写成 == 一样的错误。
        if not visited[neighbor_u]:
            new_dist = v + neighbor_v
            if new_dist < distance[neighbor_u]:  # 如果新路径更短,更新距离
                distance[neighbor_u] = new_dist
                heapq.heappush(distance_queue, (new_dist, neighbor_u))
            # heapq.heappush(distance_queue, (v + neighbor_v, neighbor_u))
        

print(distance[-1]) if distance[-1] != float("+inf") else print(-1)

Bellman_ford 算法

卡码网 94. 城市间货物运输 I
代码随想录

V, E = map(int, input().split())
 
 
graph = []
 
for i in range(E):
    s,t,v = map(int, input().split())
    graph.append((s,t,v))
 
 
distance = [float("+inf")] * (V+1)
distance[1] = 0
for i in range(1, V):
    # 如果不在更新就要退出了,如果是一个非常稀疏的图,就会超时。
    updated = False
    for s,t,v in graph:
        if distance[s] != float("+inf") and distance[s] + v < distance[t]:
            distance[t] = distance[s] + v
            updated = True
    if not updated:
        break
     
# 这个算法还可以检测负环,只要再进行一次,如果还有更新那么就有负环。
 
print(distance[-1]) if distance[-1] != float("+inf") else print("unconnected")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值