欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Ruby实现的最优二叉查找树算法

程序员文章站 2022-11-15 19:19:34
算法导论上的伪码改写而成,加上导论的课后练习第一题的解的构造函数。 复制代码 代码如下: #encoding: utf-8 =begin author: xu ji...

算法导论上的伪码改写而成,加上导论的课后练习第一题的解的构造函数。

复制代码 代码如下:

#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]}."