給定 n 個鍵 k1 < k2 < ... < kn 及其搜尋機率 p[i],以及 n+1 個虛擬鍵 (區間) 機率 q[i],構建二叉搜尋樹使預期搜尋成本最小化。
e[i][j]:區間 ki...kj 的最優預期成本。w[i][j]:區間權重和 q[i-1] + Σ(p[k]+q[k])。root[i][j]:最優根節點索引。e[i][j] = min_{r∈[i,j]} (e[i][r-1] + e[r+1][j] + w[i][j])。INF = 1.0/0.0
keys = ['', 'k1', 'k2', 'k3', 'k4', 'k5'] # 1-based
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] # 虛擬鍵機率 (0..n)
n = keys.size - 1
e = Array.new(n+2) { Array.new(n+1, 0.0) }
w = Array.new(n+2) { Array.new(n+1, 0.0) }
root = Array.new(n+2) { Array.new(n+1, 0) }
# 初始化:空區間成本 = q[i-1]
(1..n+1).each { |i| e[i][i-1] = w[i][i-1] = q[i-1] }
# 長度 1..n
(1..n).each do |len|
(1..n-len+1).each do |i|
j = i + len - 1
e[i][j] = INF
w[i][j] = w[i][j-1] + p[j] + q[j]
(i..j).each do |r|
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
# 輸出樹結構
def print_tree(root, i, j, parent=nil, dir=nil)
return if i > j
r = root[i][j]
if parent.nil?
puts "k#{r} is the root of the tree."
elsif dir == :left
puts "k#{r} is the left child of k#{parent}."
else
puts "k#{r} is the right child of k#{parent}."
end
print_tree(root, i, r-1, r, :left)
print_tree(root, r+1, j, r, :right)
end
print_tree(root, 1, n)
puts "The expected cost is #{e[1][n]}."
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.
d0..d5 表示區間d0:小於 k1 的值d1:k1 到 k2 之間d5:大於 k5 的值