14 3 DP Optimal Binary Search Trees 4up
14 3 DP Optimal Binary Search Trees 4up
14 3 DP Optimal Binary Search Trees 4up
Recursive approach: Solve a problem by solving several smaller analogous subproblems of the same type. Then combine these solutions to generate a solution to the original problem. Drawback: Repeated computation of solutions Dynamic-programming method: Once a subproblem has been solved, store its solution in a table so that it can be retrieved later by simple table lookup.
Optimal substructure
Dynamic programming is typically applied to optimization problems. An optimal solution to the original problem contains optimal solutions to smaller subproblems.
4 (-, k1) 1 k 1
3 k2
3 k 4
(k1, k2)
3 k 3
10
(k4, )
(k2, k3)
(k3, k4)
4 k2 2 k1 5 1
2 k1 4 k2
3 P(T1) = 21
5 P(T2) = 27
Goal: Binary search tree with minimum weighted path length P for S .
P(T)
ai ki Tl Tr bj kj, kj + 1
An optimal binary search tree is a binary search tree with minimum weighted path length.
If T is a tree with minimum weighted path length for S, then subtrees Tl and Tr are trees with minimum weighted path length for subsets of S.
7 Winter term 07/08 8
Let T(i, j): optimal binary search tree for (ki, ki+1) ki+1... kj (kj, kj+1), W(i, j): weight of T(i, j), i.e. W(i, j) = bi + ai+1 + ... + aj + bj , P(i, j): weighted path length of T(i, j).
T(i, l - 1)
( ki, ki + 1) ki + 1 ..... kl 1 (kl 1, kl)
T(l, j)
( kl, kl + 1) kl + 1 ..... kj (kj, kj + 1)
......
bi
......
......
......
......
......
......
......
request frequency:
ai + 1
al 1
bl 1
al
bl
al + 1
aj
bj
10
(*)
11
12
W(i ,i +1) = bi + ai+1 + bi+1 = W(i, i) + ai+1 + W(i+1, i+1) P(i, i+1) = W(i, i + 1) r(i, i +1) = i + 1
13
14
bi W (i, j ) = W (i, j 1) + a j + W ( j , j )
if i = j otherwise if i = j otherwise
Computing the solution P(0,n) takes O(n3) time. and requires O(n2) space.
Winter term 07/08 15 Winter term 07/08 16