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

所属分类: 脚本专栏 / ruby专题 阅读数: 665
收藏 0 赞 0 分享

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

复制代码 代码如下:

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

更多精彩内容其他人还在看

Ruby的面向对象编程的基础教程

这篇文章主要介绍了Ruby的面向对象编程的基础教程,包括Ruby中各种有关类和对象的基础知识,需要的朋友可以参考下
收藏 0 赞 0 分享

使用Ruby编写发送邮件的程序的简单教程

这篇文章主要介绍了使用Ruby编写发送邮件的程序的简单教程,包括发送带附件的邮件的代码实例,需要的朋友可以参考下
收藏 0 赞 0 分享

初步讲解Ruby编程中的多线程

这篇文章主要介绍了初步讲解Ruby编程中的多线程,线程是各种编程语言学习当中的重点和难点,需要的朋友可以参考下
收藏 0 赞 0 分享

使用Ruby来处理JSON的简单教程

这篇文章主要介绍了使用Ruby来处理JSON的简单教程,用到了Ruby gem,需要的朋友可以参考下
收藏 0 赞 0 分享

实例讲解Ruby中的五种变量

这篇文章主要介绍了Ruby中的五种变量,并用实例讲解了其用法,是Ruby学习当中的基础知识,需要的朋友可以参考下
收藏 0 赞 0 分享

在Ruby中创建和使用哈希的教程

这篇文章主要介绍了在Ruby中创建和使用哈希的教程,罗列了Ruby中各种使用哈希的方法,需要的朋友可以参考下
收藏 0 赞 0 分享

详解Ruby中的循环语句的用法

这篇文章主要介绍了详解Ruby中的循环语句的用法,Ruby中的循环语句与其他编程语言的相比之下显得有所不同,需要的朋友可以参考下
收藏 0 赞 0 分享

在Ruby中处理日期和时间的教程

这篇文章主要介绍了在Ruby中处理日期和时间的教程,包括时间的格式化等基本用法,需要的朋友可以参考下
收藏 0 赞 0 分享

简要说明Ruby中的迭代器

这篇文章主要介绍了Ruby中的迭代器,迭代器的概念在动态语言的编程中十分重要,文章中介绍了Ruby中的each迭代器和collect迭代器,需要的朋友可以参考下
收藏 0 赞 0 分享

在Ruby中处理文件的输入和输出的教程

这篇文章主要介绍了在Ruby中处理文件的输入和输出的教程,文中举例讲解了Ruby中各种I/O相关的方法,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多