Dynamic Programming
Dynamic Programming
Dynamic
Programming
A solution to a
problem is recursively Solutions to
Maximize or described in terms of subproblems are
minimize solutions to remembered
subproblems
F -1 -1 -1 -1 -1 -1 F 0 1 1 2 3 5
0 1 2 3 4 5 0 1 2 3 4 5
Fibonacci Number
More Efficient Recursive Fib
Example:
Let us run our algorithm on the
following data:
n = 4 (# of elements)
W = 8 (max weight capacity)
Elements (weight, benefit) :
(2, 1), (3, 2), (4, 5), (5, 6)
B[3, 5] = max{B[3-1, 5], B[3-1, 5-4] + 5} B[3, 6] = max{B[3-1, 6], B[3-1, 6-4] + 5} B[3, 7] = max{B[3-1, 7], B[3-1, 7-4] + 5}
= max{B[2, 5], B[2, 1] + 5} = max{B[2, 6], B[2, 2] + 5} = max{B[2, 7], B[2, 3] + 5}
= max{3, 0 + 5} = max{3, 1 + 5} = max{3, 2 + 5}
=5 =6 =7
0/1 Knapsack Example
n = 4 (# of elements)
W = 8 (max weight capacity)
Elements (weight, benefit) :
(2, 1), (3, 2), (4, 5), (5, 6)
Which of the items are included
and what is the maximum total
value (benefit) taken?
Weight matrix represents the distance between every pair of vertices in the form of given
weights. In constructing weight matrix, consider the following:
• For diagonal elements (representing self-loop), distance value is 0.
• For vertices having a direct edge between them, distance value is the weight of that edge.
• For vertices having no direct edge between them, distance value is ∞ .
Floyd’s Algorithm
Analysis: O(n3)
Floyd’s Algorithm
D[2, 4] = min {D[2, 4], D[2, 1] + D[1, 4]} D[3, 4] = min {D[3, 4], D[3, 1] + D[1, 4]} D[4, 3] = min {D[4, 3], D[4, 1] + D[1, 3]}
= min {∞, 2 + ∞} = min {1, ∞ + ∞} = min {∞, 6 + 3}
=∞ =1 =9
Floyd’s Algorithm
D[i, j] = min {D[i, j], D[i, k] + D[k, j]} The final matrix must not contain ∞.
Application of Floyd’s Algorithm to the given graph. Updated elements are shown in bold.
Warshall’s Algorithm
ü It computes the transitive closure of a
relation
ü Alternatively: all paths in a directed graph
ü Example of transitive closure
Warshall’s Algorithm
Main idea: a path exists between two vertices i, j, if and only if:
ü There is an edge from i to j; or
ü There is a path from i to j through vertex 1; or
ü There is a path from i to j through vertex 1 and/or 2; or
ü There is a path from i to j through vertex 1, 2 and/or 3; or
ü ….
ü There is a path from i to j going through any of the other vertices
Warshall’s Algorithm
Analysis: O(n3)
Warshall’s Algorithm
Application of Warshall’s Algorithm to the given graph. New ones are in bold.
Warshall’s Algorithm
Application of Warshall’s Algorithm to the given graph. New ones are in bold.
Q&A
Any
Question???
CP10 Dynamic Programming