Ruby-based optimal binary search tree algorithm and ruby-based optimal binary search algorithm
The pseudo code in the introduction to algorithms is rewritten, plus the constructor for the solution of the first question in the Introduction Class Exercises.
Copy codeThe Code is as follows:
# Encoding: UTF-8
= Begin
Author: xu jin
Date: Nov 11,201 2
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 cost 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]}."