Ruby實現(xiàn)的最優(yōu)二叉查找樹算法
算法導(dǎo)論上的偽碼改寫而成,加上導(dǎo)論的課后練習(xí)第一題的解的構(gòu)造函數(shù)。
#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 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]}."
相關(guān)文章
Ruby中的反射(Reflection)應(yīng)用實例
這篇文章主要介紹了Ruby中的反射(Reflection)應(yīng)用實例,實現(xiàn)通過一個類名字符串構(gòu)造一個類對象和訪問成員變量和私有方法 ,需要的朋友可以參考下2014-06-06ruby中執(zhí)行周期性任務(wù)(定時任務(wù))的3種方法
這篇文章主要介紹了ruby中執(zhí)行周期性任務(wù)(定時任務(wù))的3種方法,本文通過使用whenever、sidetiq、clockwork等gem實現(xiàn),需要的朋友可以參考下2014-10-10Ruby基本的環(huán)境變量設(shè)置以及常用解釋器命令介紹
這篇文章主要介紹了Ruby基本的環(huán)境變量設(shè)置以及常用解釋器命令介紹,是Ruby入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-10-10