迪杰斯特拉
def maxProbability(self, n, edges, succProb, start, end):
"""
:type n: int
:type edges: List[List[int]]
:type succProb: List[float]
:type start: int
:type end: int
:rtype: float
"""
r = [0]*n
mp = [{} for i in range(n)]
r[start] = 1
s = [(-1,start)]
heapq.heapify(s)
for i,(x,y)in enumerate(edges):
mp[x][y] = succProb[i]
mp[y][x] = succProb[i]
while s:
p,cur = heapq.heappop(s)
p = -p
if p < r[cur]: #因为在入队的时候可能重复,并不是最大的也入队了所以这里加个判断减少程序执行次数
continue
for neighbor,weight in mp[cur].items():
if r[neighbor] < r[cur]*weight:
r[neighbor] = r[cur]*weight
heapq.heappush(s,(-r[neighbor],neighbor))
return r[end]
弗洛伊德多源最短路(超时)
def maxProbability(self, n, edges, succProb, start, end):
"""
:type n: int
:type edges: List[List[int]]
:type succProb: List[float]
:type start: int
:type end: int
:rtype: float
"""
mp = [[0]*n for i in range(n)]
for i,(x,y)in enumerate(edges):
mp[x][y] = succProb[i]
mp[y][x] = succProb[i]
for i in range(n):
mp[i][i] = 1
for k in range(n):
for i in range(n):
for j in range(n):
if mp[i][j] < mp[i][k]*mp[k][j]:
mp[i][j] = mp[i][k]*mp[k][j]
return mp[start][end]
SPFA 用于有负权边的单源最短路问题
def maxProbability(self, n, edges, succProb, start, end):
"""
:type n: int
:type edges: List[List[int]]
:type succProb: List[float]
:type start: int
:type end: int
:rtype: float
"""
r = [0]*n
r[start] = 1
mp = [{} for i in range(n)]
for i,(x,y)in enumerate(edges):
mp[x][y] = succProb[i]
mp[y][x] = succProb[i]
queue = deque([start])
visited = set()
visited.add(start)
while queue:
cur = queue.popleft()
visited.remove(cur)
for neighbor, t in mp[cur].items():
if r[neighbor] < r[cur] * t:
r[neighbor] = r[cur]*t
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return r[end]