File size: 738 Bytes
93237a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import heapq
graph = {"A": [("B", 2), ("C", 3)], "B": [("C", 1), ("D", 4)],
         "C": [("D", 2), ("E", 3)], "D": [("E", 1)], "E": []}
dist = {v: float("inf") for v in graph}
ways = {v: 0 for v in graph}
dist["A"], ways["A"] = 0, 1
queue = [(0, "A")]
while queue:
    d, u = heapq.heappop(queue)
    if d != dist[u]:
        continue
    for v, weight in graph[u]:
        candidate = d + weight
        if candidate < dist[v]:
            dist[v], ways[v] = candidate, ways[u]
            heapq.heappush(queue, (candidate, v))
        elif candidate == dist[v]:
            ways[v] += ways[u]
result = {"distance": dist["E"], "shortest_path_count": ways["E"]}
import json
print(json.dumps(result, ensure_ascii=False, sort_keys=True))