时间:2021-05-22
算法导论上的伪码改写而成,加上导论的课后练习第一题的解的构造函数。
复制代码 代码如下:
#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]}."
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了JavaScript数据结构之二叉树的查找算法。分享给大家供大家参考,具体如下:前面文章介绍了二叉树的遍历,现在谈谈在二叉树中进行查找。对二叉查找
JavaScript中的搜索二叉树实现,供大家参考,具体内容如下二叉搜索树(BST,BinarySearchTree),也称二叉排序树或二叉查找树二叉搜索树是一
二叉排序树(BST)又称二叉查找树、二叉搜索树二叉排序树(BinarySortTree)又称二叉查找树。它或者是一棵空树;或者是具有下列性质的二叉树:1.若左子
二叉查找树性质1、二叉树每个树的节点最多有两个子节点的树叫做二叉树。2、二叉查找树一颗二叉查找树是按照二叉树的结构来组织的,并且满足一下性质:一个节点所有左子树
本文实例讲述了C语言实现二叉树的搜索及相关算法。分享给大家供大家参考,具体如下:二叉树(二叉查找树)是这样一类的树,父节点的左边孩子的key都小于它,右边孩子的