The pseudo code in the introduction of the algorithm is rewritten, coupled with the constructor of the solution of the first question in the introductory lesson practice.
#encoding: Utf-8
=begin
Author:xu Jin
Date:nov 11, 2012
Optimal Binary Search Tree
To find by using editdistance algorithm
Refer 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 of K4."
"D5 is the right child of K5."
The expected is 2.75.
=end
Infintiy = 1/0.0
A = [', ' 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 (a.size + 1) {array.new (a.size + 1)}
Root = array.new (a.size + 1) {array.new (a.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)
to 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]
&nbs p; for R in (i.. j)
t = e[i][r-1] + e[r + 1][j] + w[i][j]
&nbs p; if T < E[i][j]
e[i][j] = t
Root[i][j] = R
End
End
end
End
End
def 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
End
Optimalbst (P, Q, P.size-1, E, root)
Printbst (root, 1, a.size-1, 0)
Puts "\nthe expected cost is #{e[1][a.size-1]}."