This article mainly introduces the best binary lookup tree algorithm in Ruby, this paper gives the implementation code directly, the need for friends can refer to the following
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.
The code is as follows:
#encoding: Utf-8
=begin
Author:xu Jin
Date:nov 11, 2012
Optimal Binary Search Tree
To find by using editdistance algorithm
Refer to < >
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)
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
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]}."