Dijkstra算法
# Dijkstra算法求解单源最短路径
import heapq
MAX_DISTANCE = float('inf')
def Dijkstra(N, M):
EdgeDict = dict() # 记录各相邻顶点间的直接距离,排除重复边和自回路
for i in range(M):
src, dst = map(eval, input().strip().split())
if src == dst:
continue
currentDist = 2 ** i
EdgeDict[frozenset([src,dst])] = min([
EdgeDict.get(frozenset([src,dst]),MAX_DISTANCE),
currentDist
])
# 记录各顶点的邻接边
# MinDistDict用于保存各顶点到源点0之间的当前最短距离
AdjacentEdge, MinDistDict, VisitedVertexSet = dict(), dict(), {0}
for key, distance in EdgeDict.items():
src, dst = key
ListSrc, ListDst = AdjacentEdge.get(src, list()), AdjacentEdge.get(dst, list())
ListSrc.append((distance,dst))
ListDst.append((distance,src))
AdjacentEdge[src], AdjacentEdge[dst] = ListSrc, ListDst
#######################################################################################
priorityQueue = AdjacentEdge[0]
heapq.heapify(priorityQueue)
while len(VisitedVertexSet) < N:
edge = heapq.heappop(priorityQueue)
distance, dst = edge
if dst in VisitedVertexSet:
continue
VisitedVertexSet.add(dst)
MinDistDict[dst] = distance
for edge in AdjacentEdge[dst]:
if MinDistDict.get(edge[1],MAX_DISTANCE) > distance + edge[0]:
MinDistDict[edge[1]] = distance + edge[0]
heapq.heappush(priorityQueue,(distance + edge[0], edge[1]))
for i in range(1,N):
distance = MinDistDict.get(i, MAX_DISTANCE)
if distance == MAX_DISTANCE:
print(-1)
else:
print(distance%100000)
if __name__ == '__main__':
N, M = map(int, input().strip().split())
Dijkstra(N, M)
Bellman-Ford算法
# Bellman-Ford算法求解单源最短路径
MAX_DISTANCE = float('inf')
def Bellman_Ford(N, M):
MinimalDistanceDict = dict()
for i in range(M):
src, dst = map(eval, input().strip().split())
if src == dst:
continue
CurrentDistance = 2 ** i
if CurrentDistance < MinimalDistanceDict.get(frozenset([src,dst]), MAX_DISTANCE):
MinimalDistanceDict[frozenset([src,dst])] = CurrentDistance
for i in range(0, N):
for j in range(0, N-1):
for k in range(j+1, N):
if len({i,j,k}) < 3:
continue
if MinimalDistanceDict.get(frozenset([j, i]), MAX_DISTANCE) + \
MinimalDistanceDict.get(frozenset([i, k]), MAX_DISTANCE) < \
MinimalDistanceDict.get(frozenset([j, k]), MAX_DISTANCE):
MinimalDistanceDict[frozenset([j, k])] = \
MinimalDistanceDict.get(frozenset([j, i]), MAX_DISTANCE) + \
MinimalDistanceDict.get(frozenset([i, k]), MAX_DISTANCE)
for i in range(1,N):
distance = MinimalDistanceDict.get(frozenset([0, i]), MAX_DISTANCE)
if distance == MAX_DISTANCE:
print(-1)
else:
print(distance%100000)
if __name__ == '__main__':
N, M = map(int, input().strip().split())
Bellman_Ford(N, M)