AlgorithmThe pseudo code in the introduction is rewritten, And the constructor that solves the first question of the exercises in the Introduction Class is added.
# Encoding: UTF-8 = beginauthor: Xu jindate: Nov 11,201 2 optimal binary search treeto find by using editdistance algorithmrefer to <Introduction to algorithms> example output: "K2 is the root of the tree. "" K1 is the left child of K2. "" D0 is the left child of K1. "" d1 is the right child of K1. "" K5 is the right child of K2. "" K4 is the left child of k5. "" K3 is the left child of k4. "" D2 is the left child of K3. "" D3 is the right child of K3. "" D4 is the right child k4. "" D5 is the right child of k5. "the expected cost is 2.75. = endinfintiy = 1/0.0a = ['', 'k1 ', 'k2', 'k3', 'k4 ', 'k5'] P = [0, 0.15, 0.10, 0.05, 0.10, 0.20] q = [0.05, 0.10, 0.05, 0.05, 0.05, 0.10] e = array. new (. size + 1) {array. new (. size + 1)} root = array. new (. size + 1) {array. new (. size + 1)} def optimalbst (p, q, N, E, root) W = array. new (P. size + 1) {array. new (P. size + 1)} For I in (1 .. n + 1) E [I] [I-1] = Q [I-1] W [I] [I-1] = Q [I-1] End for L in (1 .. n) for I In (1 .. n-L + 1) j = I + L-1 E [I] [J] = 1/0.0 W [I] [J] = W [I] [J-1] + P [J] + Q [J] for R in (I .. j) T = E [I] [R-1] + E [R + 1] [J] + W [I] [J] If T <E [I] [J] e [I] [J] = t root [I] [J] = r end endenddef printbst (root, i, j, signal) return if I> j if signal = 0 p "K # {root [I] [J]} is the root of the tree. "Signal = 1 end r = root [I] [J] # Left child if R-1 <I p" d # {r-1} is the left child of K #{ r }. "Else P" K # {root [I] [R-1]} is the left child of K # {r }. "printbst (root, I, R-1, 1) end # Right child if r> = J P" d # {r} is the right child of K # {r }. "Else P" K # {root [R + 1] [J]} is the right child of K # {r }. "printbst (root, R + 1, J, 1) end endoptimalbst (p, q, P. size-1, E, root) printbst (root, 1,. size-1, 0) puts "\ nthe expected cost is # {e [1] [. size-1]}."