-
Notifications
You must be signed in to change notification settings - Fork 891
/
problem_032.py
32 lines (23 loc) · 895 Bytes
/
problem_032.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
from math import log
def arbitrage(table):
transformed_graph = [[-log(edge) for edge in row] for row in table]
# Pick any source vertex -- we can run Bellman-Ford from any vertex and
# get the right result
source = 0
n = len(transformed_graph)
min_dist = [float('inf')] * n
min_dist[source] = 0
# Relax edges |V - 1| times
for _ in range(n - 1):
for v in range(n):
for w in range(n):
if min_dist[w] > min_dist[v] + transformed_graph[v][w]:
min_dist[w] = min_dist[v] + transformed_graph[v][w]
# If we can still relax edges, then we have a negative cycle
for v in range(n):
for w in range(n):
if min_dist[w] > min_dist[v] + transformed_graph[v][w]:
return True
return False
assert arbitrage([[1, 2], [2, 1]])
assert not arbitrage([[1, 1], [1, 1]])