• 企业400电话
  • 微网小程序
  • AI电话机器人
  • 电商代运营
  • 全 部 栏 目

    企业400电话 网络优化推广 AI电话机器人 呼叫中心 网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    Ruby实现的最优二叉查找树算法

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

    复制代码 代码如下:

    #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实现的矩阵连乘算法
    • Ruby实现二分搜索(二分查找)算法的简单示例
    • Ruby实现的3种快速排序算法
    • Ruby实现的合并排序算法
    • Ruby实现的图片滤镜算法代码
    上一篇:Ruby实现的3种快速排序算法
    下一篇:Ruby实现的最短编辑距离计算方法
  • 相关文章
  • 

    © 2016-2020 巨人网络通讯 版权所有

    《增值电信业务经营许可证》 苏ICP备15040257号-8

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