-
Notifications
You must be signed in to change notification settings - Fork 0
/
offline_2_sssp.py
69 lines (49 loc) · 1.66 KB
/
offline_2_sssp.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
from collections import defaultdict
import sys
def bellman_ford(graph, source, num_of_vert, num_of_edge):
inf = float("inf")
d = {}
pi = {}
for v in graph:
d[v] = inf
pi[v] = None
d[source] = 0
for _ in range(num_of_vert-2):
for u in graph:
for v in graph[u]:
# relax(u, v, graph[u][v])
if d[v] > d[u] + graph[u][v]:
d[v] = d[u] + graph[u][v]
pi[v] = u
print('{:>12} {:>12} {:>12}'.format('V', 'Distance', 'Parent'))
for i in graph:
print('{:>12} {:>12} {:>12}'.format(str(i), str(d[i]), str(pi[i])))
for u in graph:
for v in graph[u]:
if d[v] > d[u] + graph[u][v]:
return False
return True
if __name__ == '__main__':
# f = open('offline_2_input.txt')
f = open('offline_2_input_2.txt')
num_of_tests = int(f.readline())
index_start = int(f.readline())
while(num_of_tests):
num_of_vert = int(f.readline())
num_of_edge = int(f.readline())
graph = defaultdict(dict)
for i in range(index_start, num_of_vert + index_start):
graph[i] = {}
for _ in range(0, num_of_edge):
line = f.readline().rstrip().split(" ")
graph[int(line[0])][int(line[1])] = float(line[2])
# print(graph)
for u in graph:
for v in graph[u]:
print(u, " ", v, " ", graph[u][v])
print()
print("Source?")
source = int(input())
bellman_ford(graph, source, num_of_vert, num_of_edge)
num_of_tests = num_of_tests - 1
print("End of program")