-
Notifications
You must be signed in to change notification settings - Fork 542
Expand file tree
/
Copy pathdijkstra.py
More file actions
42 lines (34 loc) · 1.12 KB
/
Copy pathdijkstra.py
File metadata and controls
42 lines (34 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from heapq import heappush, heappop
def main():
INF = int(1e9)
# Graph in Figure 4.17
# 5 7 0
# 0 1 2
# 0 2 6
# 0 3 7
# 1 3 3
# 1 4 6
# 2 4 1
# 3 4 5
f = open("dijkstra_in.txt", "r")
V, E, s = map(int, f.readline().split(" "))
AL = [[] for u in range(V)]
for _ in range(E):
u, v, w = map(int, f.readline().split(" "))
AL[u].append((v, w)) # directed graph
# (Modified) Dijkstra's routine
dist = [INF for u in range(V)]
dist[s] = 0
pq = []
heappush(pq, (0, s))
# sort the pairs by non-decreasing distance from s
while (len(pq) > 0): # main loop
d, u = heappop(pq) # shortest unvisited u
if (d > dist[u]): continue # a very important check
for v, w in AL[u]: # all edges from u
if (dist[u]+w >= dist[v]): continue # not improving, skip
dist[v] = dist[u]+w # relax operation
heappush(pq, (dist[v], v))
for u in range(V):
print("SSSP({}, {}) = {}".format(s, u, dist[u]))
main()