Algorithms Graph Theory 11 Bellman Algorithm
Algorithms Graph Theory 11 Bellman Algorithm
Competitive Programming
From Problem 2 Solution in O(1)
Graph Theory
Bellman-Ford Algorithm
1
5 -4 ● Dijkstra pick shortest(0, 2) = [0, 2] = 4, WRONG
● shortest(0, 2) = [0, 1, 3, 2] = 5-4+1 = 2
0 3
4 2 1
Bellman-Ford Algorithm
4 4 1
2
1 3
2 Positive cycle...reachable from 0
0 1 3 Bellman works
4 4 1
2
1 -4
2 Positive cycle...reachable from 0
0 1 3 Bellman works
4 4 5
Cycles
2
1 -9
2 Negative cycle of cost -5...reachable from 0
0 1 3 NO algorithms can work
2 4 1
2
1 -9
2 Negative cycle of cost -5...NOT reachable from 0
0 1 3 Bellman works
Cost for (1, 2, 3, 4) = OO
2 4 1
If added ege (7, 3) = -1, then -ve cycle is reachable
3
4 -6
5 6 7
Cycles
2
1 -9
2 Negative cycle of cost -5...reachable from 0
0 1 3 Bellman has no path to (1, 2, 3, 4)
But has to (5, 6, 7)
2 4 1
3
4 -6
5 6 7
Bellman-Ford Algorithm
3 {0, 1} = 3
2 {0, 1, 2} = 9
1 {0, 1, 4} = 4
Facts:
For each reachable node, expand it with
Expansions can be at most n-1 times every possible one edge:
To expand for k edges, you need k-1 edges results {0, 1, 2} + (2, 3, 5) => {0, 1, 2, 3} = 14
SP(S, X) uses 1 <= X <= n-1 edges {0, 1, 4} + (4, 3, 2) => {0, 1, 4, 3} = 6
max_edge = 0, j = 0
ne = {0, 1, 3}
max_edge = 0, j = 1
ne = {1, 2, 2}
max_edge = 0, j = 2
ne = {2, 3, 5}
max_edge = 1, j = 0
ne = {0, 1, 3}
max_edge = 0, j = 0
ne = {1, 2, 2}
max_edge = 0, j = 1
ne = {0, 1, 3}
max_edge = 0, j = 2
ne = {2, 3, 5}
max_edge = 1, j = 0
ne = {1, 2, 2}
max_edge = 1, j = 1
ne = {0, 1, 3}
max_edge = 1, j = 2
ne = {2, 3, 5}
(B,E)
(D,B)
(B,D)
(A,B)
(A,C)
(D,C)
(B,C)
(E,D).
Pull-Based?
Only A is reachable => Either edge A-B or A-C will be first relaxation!
Src: http://www.geeksforgeeks.org/dynamic-programming-set-23-bellman-ford-algorithm/
Bellman-Ford Tracing
(B,E)
(D,B)
(B,D)
(A,B)
(A,C)
(D,C)
(B,C)
(E,D).
Pull-Based?
A is reachable => Active edges {A-B, A-C}
B is reachable => Active edges {B-C, B-D, B-E}
C is reachable => Active edges {}
Src: http://www.geeksforgeeks.org/dynamic-programming-set-23-bellman-ford-algorithm/
Bellman-Ford Tracing
(B,E)
(D,B)
(B,D)
(A,B)
(A,C)
(D,C)
(B,C)
(E,D).
Src: http://www.geeksforgeeks.org/dynamic-programming-set-23-bellman-ford-algorithm/
Bellman-Ford Algorithm: improvement
ﻋﻠﻤﻜﻢ ﷲ ﻣﺎ ﯾﻨﻔﻌﻜﻢ
وزادﻛﻢ ﻋﻠﻤﺎ ً