Professional Documents
Culture Documents
Dynamic Programming
Dynamic Programming
A1. A2 … An
The way we parenthesize a chain of matrices can have a dramatic impact on the
cost of evaluating the product
• Consider the problem of a chain ( A1, A2, A3) of three matrices.
m[i, j] = 0 if i=j
s[i, j] = k // represents the value of k at which
we apply parenthesis.
• For finding multiplication of A1, A2 … A6
matrices.
P0 = 30
P1 = 35
P2 = 15
P3 = 5
P4 = 10
P5 = 20
P6 = 25
m[1, 2] = m[1,1] + m[2, 2] + P0 . P1 . P2 m[1, 3] when k=1
= 0 + 0 + 30 . 35 . 15 = m[1, 1] + m[2, 3] + P0 . P1 . P3
m[2, 3] = m[2, 2] + m[3, 3] + P1 . P2 . P3 = 0 + 2625 + 30 . 35 . 5 = 7875
= 0 + 0 + 35 . 15 . 5 m[1, 3] when k=2
m[3, 4] = = m[1, 2] + m[3, 3] + P0 . P2 . P3
m[4, 5] = = 15,750 + 0 + 30 . 15 . 5
m[5, 6] =
Print_optimal(S, i,j)
{
if(i == j)
print Ai
else
{
print “(“
Print_optimal(S, i ,s[i,j])
Print_optimal(S, s[i,j]+1 ,j);
print “)”
}
}
Time complexity
• if we have n matrices to multiply, it will take
O(n) time to generate each of the O(n2) costs
and entries in the best matrix for an overall
complexity of O(n3) time at a cost of O(n2)
space.
All pairs shortest path Algorithm
Algorithm AllPaths(cost, A, n]
{
for(i=1 to n) do
for(j=1 to n) do
A[i, j] = cost[i, j];
for(k=1 to n) do
for(i=1 to n) do
for(j=1 to n) do
A[i, j] = min(A[i, j], A[i, k] + A[k, j]);
}
Example
OBST
Algorithm OBST(p, q, n)
{
for(i=0 to n-1)
{
w[i, i] = q[i]; c[i, i] = 0; r[i, i] = 0;
c[i, i+1] = w[i, i+1] = q[i] + q[i+1] + p[i+1];
r[i, i+1] = i+1;
}
w[n, n] = q[n]; c[n, n] = 0; r[n, n] = 0;
for(m=2 to n)
{
for(i=0 to (n-m))
{
j = i+m;
w[i, j] = w[i, j-1] + q[j] + p[j];
k = find[c , i, r, j];
c[i, j] = w[i, j] + c[i, k-1] + c[k,j];
r[i, j] = k;
}
}
}