算法导论上的伪码改写而成,加上导论的课后练习第一题的解的构造函数。
复制代码 代码如下:
#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]}."
Ruby,二叉查找树,算法
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
更新日志
- 雨林唱片《赏》新曲+精选集SACD版[ISO][2.3G]
- 罗大佑与OK男女合唱团.1995-再会吧!素兰【音乐工厂】【WAV+CUE】
- 草蜢.1993-宝贝对不起(国)【宝丽金】【WAV+CUE】
- 杨培安.2009-抒·情(EP)【擎天娱乐】【WAV+CUE】
- 周慧敏《EndlessDream》[WAV+CUE]
- 彭芳《纯色角3》2007[WAV+CUE]
- 江志丰2008-今生为你[豪记][WAV+CUE]
- 罗大佑1994《恋曲2000》音乐工厂[WAV+CUE][1G]
- 群星《一首歌一个故事》赵英俊某些作品重唱企划[FLAC分轨][1G]
- 群星《网易云英文歌曲播放量TOP100》[MP3][1G]
- 方大同.2024-梦想家TheDreamer【赋音乐】【FLAC分轨】
- 李慧珍.2007-爱死了【华谊兄弟】【WAV+CUE】
- 王大文.2019-国际太空站【环球】【FLAC分轨】
- 群星《2022超好听的十倍音质网络歌曲(163)》U盘音乐[WAV分轨][1.1G]
- 童丽《啼笑姻缘》头版限量编号24K金碟[低速原抓WAV+CUE][1.1G]