L26 DynamicProgramming III
L26 DynamicProgramming III
X = A, B, D, E
Y = Z, B, E
j
• Store the value of yj: y1 y2 yn
the c[i,j] in a table 0 xi 0 0 0 0 0 0
Compute the 1 x1 first
0
entries in a row-
2 x2 0 second
major order i
0
0
m xm 0
0 1 2 n
MA512: Data Structures and Algorithms
16
Additional information
A matrix b[i, j]:
• For a subproblem [i, j] it 0 1 2 3 n
tells us what choice was b & c: yj: A C D F
made to obtain the 0 xi 0 0 0 0 0 0
optimal value 1 A 0
• If xi = yj
2 B
b[i, j] = “ ” 0 c[i-1,j]
i
• Else, if c[i - 1, j] ≥ c[i, j-1] 3 C 0 c[i,j-1]
b[i, j] = “ ” 0
else m D 0
b[i, j] = “ ”
j
19
4. Constructing a LCS
• Start at b[m, n] and
follow the arrows 0 1 2 3 4 5 6
• When we encounter yj B D C A B A
a “ “ in b[i, j] 0 xi 0 0 0 0 0 0 0
xi = yj is an 1 A 0
0
0
0 1 1 1
element of the LCS 2 B
0 1 1 1 1 2 2
3 C
0 1 1 2 2 2 2
4 B
0 1 1 2 2 3 3
5 D
0 1 2 2 2 3 3
6 A 0 1 2 2 3 3 4
7 B 0 1 2 2 3 4 4
20
PRINT-LCS(b, X, i, j)
1. if i = 0 or j = 0 Running time: (m + n)
2. then return
3. if b[i, j] = “ ”
4. then PRINT-LCS(b, X, i - 1, j - 1)
5. print xi
6. elseif b[i, j] = “↑”
7. then PRINT-LCS(b, X, i - 1, j)
8. else PRINT-LCS(b, X, i, j - 1)
Initial call: PRINT-LCS(b, X, length[X], length[Y])
21
Improving the Code
• What can we say about how each entry c[i, j] is
computed?
It depends on c[i -1, j - 1], c[i - 1, j], and c[i, j - 1]
Eliminate table b and compute in O(1) which of the
three values was used to compute c[i, j]
We save (mn) space from table b
However, we do not asymptotically decrease the
auxiliary space requirements: still need table c