-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdijkstra.py
69 lines (49 loc) · 1.66 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
# -*- coding: utf-8 -*-
"""
Usage:
n, m = map(int, input().split())
edges = [[] for _ in range(n)]
for _ in range(m):
ai, bi, ci = map(int, input().split())
ai -= 1
bi -= 1
# ci: cost
# bi: edge (0-indexed)
edges[ai].append((ci, bi))
dist, _ = dijkstra(vertex_count=n, source=0, edges=edges)
"""
def dijkstra(vertex_count: int, source: int, edges):
"""Uses Dijkstra's algorithm to find the shortest path in a graph.
Args:
vertex_count: The number of vertices.
source : Vertex number (0-indexed).
edges : List of (cost, edge) (0-indexed).
Returns:
costs : List of the shortest distance.
parents: List of parent vertices.
Landau notation: O(|Edges|log|Vertices|).
See:
https://atcoder.jp/contests/abc191/submissions/19964078
https://atcoder.jp/contests/abc191/submissions/19966232
"""
from heapq import heappop, heappush
hq = [(0, source)] # weight, vertex number (0-indexed)
costs = [float("inf") for _ in range(vertex_count)]
costs[source] = 0
visited = [False for _ in range(vertex_count)]
pending = -1
parents = [pending for _ in range(vertex_count)]
while hq:
cost, vertex = heappop(hq)
if cost > costs[vertex]:
continue
if visited[vertex]:
continue
visited[vertex] = True
for weight, edge in edges[vertex]:
new_cost = cost + weight
if new_cost < costs[edge]:
costs[edge] = new_cost
parents[edge] = vertex
heappush(hq, (new_cost, edge))
return costs, parents