Professional Documents
Culture Documents
Winter 2024
s n o w y s n o w y
s u n n y s u n n y
3C 1A, 1C, 1D
s n o w y
s u n n y
2A, 1C, 2D
Examples: DNA sequences made of a, c, g, t
The algorithm computes all D[i, j], using two nested loops, so
runtime Θ(mn)
Output:
an optimal BST with keys 1, . . . , n
Pn
optimal: minimizes i=1 pi · (depth(i) + 1) = expected
number of tests for a search
Output:
an optimal BST with keys 1, . . . , n
Pn
optimal: minimizes i=1 pi · (depth(i) + 1) = expected
number of tests for a search
Example: p1 = p2 = p3 = p4 = p5 = 1/5: ?
Output:
an optimal BST with keys 1, . . . , n
Pn
optimal: minimizes i=1 pi · (depth(i) + 1) = expected
number of tests for a search
Example: p1 = p2 = p3 = p4 = p5 = 1/5: ?
See also
optimal static ordering for linked lists
Huffman trees
both built using greedy algorithms
Recurrence
k−1
X j
X
M [i, j] = min M [i, k − 1] + pℓ + pk + M [k + 1, j] + pℓ
i≤k≤j
ℓ=i ℓ=k+1
j
X
= min M [i, k − 1] + M [k + 1, j] + pℓ
i≤k≤j
ℓ=i
Pj
Remark: to get ℓ=i pℓ :
compute S[ℓ] = p1 + · · · + pℓ , for ℓ = 1, . . . , n
then pi + · · · + pj = S[j] − S[i − 1], with S[0] = 0
OptimalBST(p1 , . . . , pn , S0 , . . . , Sn )
1. for i = 1, . . . , n + 1
2. M [i, i − 1] ← 0
3. for d = 0, . . . , n − 1 d=j−i
4. for i = 1, . . . , n − d
5. j ←d+i
6. M [i, j] ← mini≤k≤j (M [i, k − 1] + M [k + 1, j]) + S[j] − S[i − 1]
Runtime O(n3 )
1 2
4 3
S = {1, 3}.
A. Jamshidpey Y. Lu (CS, UW) Lec 13: DP Part 3 Winter 2024 7/8
Algorithm (sketch)
X X
I(v) = max{1 + I(u), I(u)}
grandchildren u of v children u of v