17 Dynprog2
17 Dynprog2
Dynamic Programming
Programming
c[springtime, printing]
•top/down p
r
•bottom/up i
n
g
t
i
m
Comp 122, Spring Lin / Devi
nprog - 14 e
2004
Computing the length of an LCS
LCS-LENGTH
LCS-LENGTH(X, (X,Y) Y)
1.1. mm←←length[X]
length[X]
2.2. nn←←length[Y]
length[Y]
3.3. for
forii←
←11to tomm
4.4. do
doc[i,
c[i,0]
0]← ←00
5.5. for
forjj←
←00to tonn
6.6. do
doc[0,
c[0,jj]]← ←00 b[i, j ] points to table entry
7.7. for
forii←
←11to tomm whose subproblem we used
8.8. do
dofor
forjj← ←11to tonn
9.9. do in solving LCS of Xi
doififxxi i==yyj j
10.
10. then
thenc[i, c[i,jj]]← ←c[i c[i1,1,j
j1]1]++11 and Yj.
11.
11. b[i,
b[i,jj]]← ←““ ””
12.
12. else
elseififc[i c[i1,1,jj]]≥≥c[i,
c[i,j j1]
1] c[m,n] contains the length
13.
13. then
thenc[i, c[i,jj]]←←c[i c[i1,1,jj]] of an LCS of X and Y.
14.
14. b[i,
b[i,jj]]← ←“↑” “↑”
15.
15. else
elsec[i,
c[i,jj]]← ←c[i,c[i,j j1]
1]
16.
16. b[i,
b[i,jj]]← ←“←” “←”
Time: O(mn)
17.
17.return
returnccandandbb
Comp 122, Spring Lin / Devi
nprog - 15
2004
Constructing an LCS
PRINT-LCS
PRINT-LCS(b, (b,X,
X,i,i,j)j)
1.1. ififii==00ororjj==00
2.2. then thenreturn
return
3.3. ififb[i,
b[i,jj]]==““ ””
4.4. then thenPRINT-LCS(b,
PRINT-LCS(b,X, X,ii1,
1,jj1)
1)
5.5. print
printxxi i
6.6. elseif
elseifb[i,
b[i,jj]]==“↑”
“↑”
7.7. then
thenPRINT-LCS(b,
PRINT-LCS(b,X, X,ii1,
1,j)j)
8.8. else
elsePRINT-LCS(b,
PRINT-LCS(b,X, X,i,i,jj1)
1)
k2 i depthT(ki) depthT(ki)·pi
1 1 0.25
2 0 0
k1 k5 3 3 0.15
4 2 0.4
5 1 0.3
1.10
k4
Therefore, E[search cost] = 2.10.
T
ki kr-1 kr+1 kj
To find an optimal BST:
» Examine all candidate roots kr , for i ≤ r ≤ j
» Determine all optimal BSTs containing ki,...,kr1 and
containing kr+1,...,kj
Comp 122, Spring Lin / Devi
nprog - 24
2004
Recursive Solution
Find optimal BST for ki,...,kj, where i ≥ 1, j ≤ n, j ≥ i1.
When j = i1, the tree is empty.
Define e[i, j ] = expected search cost of optimal BST for ki,...,kj.
Time: O(n3)
Comp 122, Spring Lin / Devi
nprog - 28
2004
Elements of Dynamic Programming
Optimal substructure
Overlapping subproblems