UNIT 4 Dynamic Programming
UNIT 4 Dynamic Programming
• Main idea:
- set up a recurrence relating a solution to a larger instance
to solutions of some smaller instances
- solve smaller instances once
- record solutions in a table
- extract solution to the initial instance from that table
Example 1: Fibonacci numbers
• Recall definition of Fibonacci numbers:
F(n)
F(n-1) + F(n-2)
F(0) = 0
F(1) = 1
F(2) = 1+0 = 1
…
F(n-2) =
F(n-1) =
F(n) = F(n-1) + F(n-2)
3 3
1 1
0 0 1 0 0 0 1 0
1 0 0 1 1 1 1 1
4 0 0 0 0 4 0 0 0 0
2 2 1 1 1 1
0 1 0 0
Warshall’s Algorithm (recurrence)
On the k-th iteration, the algorithm determines for every pair of
vertices i, j if a path exists from i and j with just vertices 1,…,k
allowed as intermediate
{
R(k)[i,j] =
R(k-1)[i,j]
or
(path using just 1 ,…,k-1)
j
Warshall’s Algorithm (matrix generation)
Recurrence relating elements R(k) to elements of R(k-1) is:
4 4 4 2 4 4
2 2 2 2
3
1 0 0 1 0 0 0 1 0
1 0 0 1 1 0 1 1
R(0) =
0 0 0 0 R(1) =
0 0 0 0
2 4
0 1 0 0 0 1 0 0
0 0 1 0 0 0 1 0 0 0 1 0
1 0 1 1 1 0 1 1 1 1 1 1
R(2) =
0 0 0 0 R(3) =
0 0 0 0 R(4) =
0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
Warshall’s Algorithm (pseudocode and analysis)
Example: 4 3
1
1
6
1 5
4
2 3
Floyd’s Algorithm (matrix generation)
On the k-th iteration, the algorithm determines shortest paths
between every pair of vertices i, j that use only vertices among
1,…,k as intermediate
D(k-1)[i,k]
k
i
D(k-1)[k,j]
D(k-1)[i,j]
j
Floyd’s Algorithm (example)
2
1 2 0 ∞ 3 ∞ 0 ∞ 3 ∞
3 6 7 2 0 ∞ ∞ 2 0 5 ∞
D(0) =
∞ 7 0 1 D(1) =
∞ 7 0 1
3
1
4 6 ∞ ∞ 0 6 ∞ 9 0
0 ∞ 3 ∞ 0 10 3 4 0 10 3 4
2 0 5 ∞ 2 0 5 6 2 0 5 6
D(2) =
9 7 0 1 D(3) =
9 7 0 1 D(4) =
7 7 0 1
6 ∞ 9 0 6 16 9 0 6 16 9 0
optimal BST
A
optimal BST
A
optimal BST
A
optimal BST
A
k-1
∑ ps · (level as in T[i,k-1] +1) +
Optimal Optimal s=i
BST for BST for
a i , ..., a k-1 a k+1 , ..., a j j
∑ ps · (level as in T[k+1,j] +1)}
s =k+1
DP for Optimal BST Problem (cont.)
After simplifications, we obtain the recurrence for C[i,j]:
j
C[i,j] = min {C[i,k-1] + C[k+1,j]} + ∑ ps for 1 ≤ i ≤ j ≤ n
i≤k≤j s=i
C[i,i] = pi for 1 ≤ i ≤ j ≤ n
1 0 p1 goal
0 p2
i C[i,j]
pn
n+1 0
Example: key A B C D
probability 0.1 0.2 0.4 0.3
2 2 3 3 B D
2 0 .2 .8 1.4
3 0 .4 1.0 3 3 3
A
4 0 .3 4 4
optimal BST
5 0 5