dijkstra_text = """
{
0:[(2,0.26),(4,0.38)],
1:[(3,0.29)],
2:[(7,0.34)],
3:[(6,0.52)],
4:[(7,0.37),(5,0.35)],
5:[(1,0.32),(7,0.28),(4,0.35)],
6:[(4,0.93),(0,0.58),(2,0.40)],
7:[(3,0.39),(5,0.28)]
}
"""
import mst
MAX_VALUE = 2**31 - 1
g = eval(dijkstra_text)
mst.fill(g)
def dijkstra(g,source):
where_from = dict()
dist_to = dict()
pq = mst.Min_PQ_(lambda x:x[-1])
for v in g:
dist_to[v] = MAX_VALUE
dist_to[source] = 0
pq.insert((source, 0))
def relax(v):
for e in g.get(v,[]):
target,weight = e[1],e[-1]
if dist_to[target]>dist_to[v]+weight:
dist_to[target] = dist_to[v]+weight
where_from[target]=v
for i in range(0,len(pq.data)):
if pq.data[i][0] == target:
## tuple 不可变
pq.data[i] = (target,dist_to[target])
break
else:
pq.insert((target,dist_to[target]))
while pq:
## 返回的是tuple需要用两个参数接收
v,d = pq.remove()
relax(v)
return where_from
print(dijkstra(g,0))