-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstra.py
More file actions
64 lines (54 loc) · 1.56 KB
/
dijkstra.py
File metadata and controls
64 lines (54 loc) · 1.56 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)
n, m = map(int, input().split())
start = int(input())
graph = [[] for i in range(n + 1)]
# visited = [False] * (n + 1)
distance = [INF] * (n + 1)
for _ in range(m):
a, b, c = map(int, input().split())
graph[a].append((b, c))
# b : node // c : cost
# O(n)
# def get_small_node():
# min_value = INF
# index = 0
# for i in range(1, n + 1):
# if distance[i] < min_value and not visited[i]:
# min_value = distance[i]
# index = i
# return index
# O(n2)
# def dijkstra(start):
# distance[start] = 0
# visited[start] = True
# for j in graph[start]:
# distance[j[0]] = j[1]
# for i in range(n - 1): # O(n)
# now = get_small_node() # O(n)
# visited[now] = True
# for j in graph[now]:
# cost = distance[now] + j[1]
# if cost < distance[j[0]]:
# distance[j[0]] = cost
def dijkstra(start):
q = []
heapq.heappush(q, (0, start))
distance[start] = 0
while q:
dist, now = heapq.heappop(q)
if distance[now] < dist:
continue
for i in graph[now]:
cost = dist + i[1]
if distance[i[0]] > cost:
distance[i[0]] = cost
heapq.heappush(q, (cost, i[0]))
dijkstra(start)
for i in range(1, n + 1):
if distance[i] == INF:
print("INFINITY")
else:
print(i, "node :", distance[i])