AcWing 851. spfa求最短路-python
原题链接
简单
作者:
Actor丶
,
2020-02-22 12:09:17
,
所有人可见
,
阅读 1197
"""
基本思想:
用队列优化Bellman-Fold算法,长得有点像堆优化的Dijkstra算法
在a->b的边中,Bellman-Fold算法的更新公式为:dist[b] = min(dist[b], dist[a]+weight),若想dist[b]变小,则dist[a]一定需要变小
SPFA算法模板:
def spfa():
dist = [float("inf") for i in range(n+1)]
dist[1] = 0
queue = [1]
st[1] = True # !!!注意,st数组用来标记节点i是否在queue中
while queue:
t = queue.pop(0)
st[t] = False
if t not in graph: continue
for weight, node in graph[t]:
if dist[node]>dist[t]+weight: # !!!注意:判断dist[t]是否变小,变小则更新距离,同时将node添加到队列中
dist[node] = dist[t] + weight
if st[node]==False: # node不在队列中
queue.append(node)
st[node] = True
if dist[n]>=float("inf")/2:
return -1
else:
return dist[n]
"""
def spfa():
dist = [float("inf") for i in range(n+1)]
dist[1] = 0
queue = [1]
st[1] = True # !!!注意,st数组用来标记节点i是否在queue中
while queue:
t = queue.pop(0)
st[t] = False
if t not in graph: continue
for weight, node in graph[t]:
if dist[node]>dist[t]+weight:
dist[node] = dist[t] + weight
if st[node]==False: # node不在队列中
queue.append(node)
st[node] = True
if dist[n]>=float("inf")/2:
return -1
else:
return dist[n]
# 输入示例
if __name__=="__main__":
n, m = map(int, input().split())
st = [False for i in range(n+1)] # !!!注意,st用来标记节点i是否在queue中
# 带权图的存储模板
graph = {}
while m:
x, y, z = map(int, input().split())
if x not in graph:
graph[x] = [(z, y)]
else:
graph[x].append((z, y))
m -= 1
res = spfa()
print(res) if res!= -1 else print("impossible")
错的0....0