This repository was archived by the owner on Mar 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijkstra.py
69 lines (53 loc) · 1.56 KB
/
dijkstra.py
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Uses python3
##############################
# @author Daniel Avdar
# @input: #edges, #vertices (one line)
# the graph's edges (following lines)
# the vertices s,t to find the path between them (last line)
# @output: the minimum weight of a path from s to t,
# or −1 if there is no path.
# @description: Dijkstra algorithm for finding the shortest path in a weighted graph
#
##############################
import sys
import heapq
from numpy import inf
heap = []
def generateDWGraph(edges, n):
graph = {}
for i in range(1, n + 1):
graph[i] = [False, dict(), None, [inf, i]]
heap.append(graph[i][3])
for ((a, b), w) in edges:
graph[a][1][b] = w
return graph
def distance(graph, s, t):
heap_ = heap
def set_v(v, w):
graph[v][3][0] = min(w, graph[v][3][0])
set_v(s, 0)
heapq.heapify(heap_)
while heap_:
w, v = heapq.heappop(heap_)
graph[v][0] = True
for i in graph[v][1].keys():
if graph[i][0]:
continue
set_v(i, w + graph[v][1][i])
heapq.heapify(heap_)
return graph[t][3][0] if graph[t][3][0] != inf else -1
def main():
input_ = sys.stdin.read()
data = list(map(int, input_.split()))
n, m = data[0:2]
data = data[2:]
edges = list(zip(zip(data[0:(3 * m):3], data[1:(3 * m):3]), data[2:(3 * m):3]))
if not data:
print(0)
return
s, t = data[-2], data[-1]
g = generateDWGraph(edges, n)
print(distance(g, s, t))
if __name__ == '__main__':
main()
# todo git