AcWing 851. spfa求最短路 python
原题链接
简单
作者:
申侠
,
2020-10-22 21:43:52
,
所有人可见
,
阅读 377
class Graph(object):
def __init__(self, n, N=100010):
self.h = [-1] * N
self.e = [-1] * N
self.w = [-1] * N
self.ne = [-1] * N
self.idx = 0
self.n = n
def add(self,a,b,c):
idx = self.idx
self.e[idx] = b
self.w[idx] = c
self.ne[idx] = self.h[a]
self.h[a] = idx
self.idx += 1
def spfa(self,s,u):
from queue import Queue
q = Queue()
p = [float('inf')] * (self.n+1)
st = [False] * (self.n+1)
p[s] = 0
st[s] = True
q.put(s)
while not q.empty():
d = q.get()
st[d] = False
i = self.h[d]
while i!= -1:
v = self.e[i]
w = self.w[i]
if p[v] > p[d] + w:
p[v] = p[d] + w
if not st[v]:
q.put(v)
st[v] = True
i = self.ne[i]
return 'impossible' if p[u] == float('inf') else p[u]
n,m = map(int, input().split(' '))
g = Graph(n)
for _ in range(m):
a, b, c = map(int, input().split(' '))
g.add(a,b,c)
print(g.spfa(1,n))
为啥不能ac呢