Ruby實現的最優二叉查詢樹演算法

2022-09-26 05:33:10 字數 2133 閱讀 2922

演算法導論上的偽碼改寫而成,加上導論的課後練習第一題的解的建構函式。

複製** **如下:

#encoding: utf-8

=begin

author: xu jin

date: nov 11, 2012

optimal binary search tree

to find by using editdistance algoribxomdthm

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 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)

root = array.new(a.size + 1)

def optimalbst(p, q, n, e, root)

w = 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]

endforbxomd 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

endend

endend

enddef printbst(root, i ,j, signal)

return if i > j

if signal == 0

p "k# is the root of the tree."

signal = 1

endr = root[i][j]

#left child

if r - 1< i

p "d# is the left child of k#."

else

程式設計客棧 p "k# is the left child of k#."

printbst(root, i, r - 1, 1 )

end#right child

if r >= j

p "d# is the right child of k#."

else

p "k# is the right child of k#."

printbst(root, r + 1, j, 1)

endend

optimalbst(p, q, p.size -bxomd 1, e, root)

printbst(root, 1, a.size-1, 0)

puts "\nthe expected cost is #."

本文標題: ruby實現的最優二叉查詢樹演算法

本文位址:

最優二叉查詢樹

1.演算法講解見 演算法設計與分析基礎 p223 p227 2.關於如何確定迴圈的值,見下圖 可得到下表 很顯然,d作為最外層迴圈,i為次外層,而j作為i的因變數存在。i 1 n d 相應的j i d k作為最記憶體迴圈,每次開始迴圈時,始終用temp儲存此次迴圈的最小值,即 3.如下 includ...

最優二叉查詢樹

問題描述 對於給定的一組改路,構造乙個期望搜尋代價最小的二叉查詢樹。演算法導論 第二版213頁。include include using namespace std define key number 5 define infinity 1000 期望搜尋代價,只使用1 i n 1,0 j n的表...

最優二叉查詢樹(optimal BST)

最優二叉查詢樹 一棵有n個結點的二叉查詢樹,已知每個結點的查詢概率pi 且 pi 1 要使查詢操作的平均比較次數最小。這裡討論的是成功查詢,不討論不成功的查詢 動態規劃 c i j 表示由結點i j組成的bst成功查詢的最小平均查詢次數。r i j 表示由結點i j構成最優二叉查詢樹時的樹根結點。轉...