萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Ruby 實現最優二叉搜尋樹 (OBST):動態規劃構造、預期成本最小化、樹結構輸出

問題定義

給定 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 的值

複雜度分析

  • 時間:O(n³) 三層迴圈 (長度、起點、根嘗試)。
  • 空間:O(n²) 儲存 e、w、root 表。
  • Knuth 優化可降至 O(n²) (單調性條件滿足時)。

應用場景

  • 編譯器關鍵字/保留字查找表優化。
  • 資料庫索引結構設計。
  • 靜態字典、路由表等已知查詢分佈的查找優化。
copyright © 萬盛學電腦網 all rights reserved