AcWing 853. Bellman_Ford PYTHON3
原题链接
简单
作者:
Gyp
,
2020-03-14 17:33:22
,
所有人可见
,
阅读 562
n, m, k = map(int, input().split())
## 用一个list 记录所有边的信息即可
g = []
dist = [float("inf") for i in range(n+1)]
for i in range(m):
a, b, w = map(int, input().split())
g.append([a, b, w])
def bellman_ford():
dist[1] = 0
## 循环几次代表最多用几条边
for _ in range(k):
## 必须backup 防止在过程中会更新dist里面的数据导致并不是最多k条边
backup = dist[:]
for i in range(m):
a, b, w = g[i][0], g[i][1], g[i][2]
dist[b] = min(dist[b], backup[a] + w)
bellman_ford()
print(dist[n] if dist[n] != float("inf") else "impossible")