Lecture 17 - Bellman-Ford and Arbitrage: Eric A. Autry
Lecture 17 - Bellman-Ford and Arbitrage: Eric A. Autry
Eric A. Autry
1 / 31
Last time: Dijkstra’s Algorithm
2 / 31
Dijkstra’s Algorithm Implementation
def dijkstra(graph, start):
# Set initial dist and prev.
for vertex in graph:
vertex.dist = ∞
vertex.prev = null
start.dist = 0
# Make the queue out of the distances.
queue = makequeue(dists)
# Loop while there are vertices left to visit.
while not queue.isEmpty():
# Find the next vertex to visit.
u = deletemin(queue)
# Check each neighbor of u.
# Update predictions and previous vertex.
for neighbor of u:
if neighbor.dist > u.dist + length(u, neighbor):
neighbor.dist = u.dist + length(u, neighbor)
neighbor.prev = u
decreasekey(queue, neighbor)
3 / 31
Dijkstra’s Algorithm
Main Idea:
I Make distance predictions.
I Iteratively find the next closest vertex.
I Then use that vertex to update the predictions.
Major Assumption:
I Every vertex on the shortest path from the start to vertex v
is closer to the start than vertex v.
Problem:
I What happens if we have negative cost edges?
4 / 31
Negative Cost Edges
Problem:
I What happens if we have negative cost edges?
5 / 31
Safe Updates
What can we do? We would still like to use the major idea of
Dijkstra’s algorithm if possible.
They start at infinity and are only ever updated along an edge
from u to v following the rule:
6 / 31
Safe Updates
Distances are updated following the rule:
7 / 31
Sequences of Safe Updates
8 / 31
Sequences of Safe Updates
Can we find a sequence of updates that will give us the correct
answer?
s → u1 , u1 → u2 , u2 → u3 , ..., uk → t
Idea: update along all of the edges in the graph |V| − 1 times.
11 / 31
Bellman-Ford Example
12 / 31
Bellman-Ford Example
Cost/Prev:
Cost/Prev:
14 / 31
Bellman-Ford Example
Cost/Prev:
15 / 31
Bellman-Ford Example
Cost/Prev:
16 / 31
Bellman-Ford Example
Cost/Prev:
17 / 31
Bellman-Ford Example
Cost/Prev:
18 / 31
Bellman-Ford Example
Cost/Prev:
19 / 31
Bellman-Ford Example
Cost/Prev:
20 / 31
Bellman-Ford Example
Cost/Prev:
21 / 31
Bellman-Ford Example
Cost/Prev:
22 / 31
Bellman-Ford Runtime
O(|V| · |E|)
23 / 31
Negative Cost Cycles
What happens if we change the weight of the edge between E
and B to −4?
25 / 31
Negative Cost Cycles
Shortest path algorithms are invalid when negative cost cycles
exist because there cannot be shortest paths!
26 / 31
Negative Cost Cycles
Application: finance.
Say that:
I 1 USD buys 0.82 Euro,
I 1 Euro buys 129.7 Yen,
I 1 Yen buys 12 Turkish Lira,
I 1 Turkish Lira buys 0.0008 USD
We made a 2% profit!
1 1 1
log + log + · · · + log < 0.
R(c1 , c2 ) R(c2 , c3 ) R(ck , c1 )
28 / 31
Negative Cost Cycles
We are looking for a cycle of currencies such that
1 1 1
log + log + · · · + log < 0.
R(c1 , c2 ) R(c2 , c3 ) R(ck , c1 )
1
length(u,v) = log = − log R(u, v).
R(u, v)
http://duke.is/xdRkXT