AcWing 853. 有边数限制的最短路-python
原题链接
简单
作者:
Actor丶
,
2020-02-21 09:53:17
,
所有人可见
,
阅读 685
"""
基本思想:bellmanFold模板:
步骤: 1.控制最短路的最大边数;2. 遍历图的所有边
def bellmanFold():
dist = [float("inf") for i in range(n+1)]
dist[1] = 0
for i in range(0,k): # 1.控制最短路的最大边数
distCopy = dist.copy() # 注意,在求有边数限制的最短路时,一定要对dist进行备份,以防止在后面遍历边时出现串联问题
for x,y,z in edge: # 2. 遍历图的所有边
if dist[y]>distCopy[x]+z:
dist[y] = distCopy[x]+z
if dist[n]>= float("inf")/2.0:
return -1
else:
return dist[n]
"""
def bellmanFold():
dist = [float("inf") for i in range(n+1)]
dist[1] = 0
for i in range(0,k): # 1.控制最短路的最大边数
distCopy = dist.copy() # 注意,在求有边数限制的最短路时,一定要对dist进行备份,以防止在后面遍历边时出现串联问题
for x,y,z in edge: # 2. 遍历图的所有边
if dist[y]>distCopy[x]+z:
dist[y] = distCopy[x]+z
if dist[n]>= float("inf")/2.0:
return -1
else:
return dist[n]
if __name__=="__main__":
n,m,k = map(int, input().split())
edge = [] # 存储图的所有边
while m:
x, y, z = map(int, input().split())
edge.append((x, y, z))
m -= 1
res = bellmanFold()
print(res) if res!=-1 else print("impossible")