佳木斯湛栽影视文化发展公司

主頁 > 知識(shí)庫 > Ruby實(shí)現(xiàn)的最優(yōu)二叉查找樹算法

Ruby實(shí)現(xiàn)的最優(yōu)二叉查找樹算法

熱門標(biāo)簽:Win7旗艦版 語音系統(tǒng) 企業(yè)做大做強(qiáng) 電話運(yùn)營中心 硅谷的囚徒呼叫中心 百度AI接口 客戶服務(wù) 呼叫中心市場需求

算法導(dǎo)論上的偽碼改寫而成,加上導(dǎo)論的課后練習(xí)第一題的解的構(gòu)造函數(shù)。

復(fù)制代碼 代碼如下:

#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實(shí)現(xiàn)的各種排序算法
  • ruby實(shí)現(xiàn)的插入排序和冒泡排序算法
  • Ruby實(shí)現(xiàn)的矩陣連乘算法
  • Ruby實(shí)現(xiàn)二分搜索(二分查找)算法的簡單示例
  • Ruby實(shí)現(xiàn)的3種快速排序算法
  • Ruby實(shí)現(xiàn)的合并排序算法
  • Ruby實(shí)現(xiàn)的圖片濾鏡算法代碼

標(biāo)簽:喀什 崇左 海南 長沙 山西 安康 山西 濟(jì)南

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Ruby實(shí)現(xiàn)的最優(yōu)二叉查找樹算法》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    樟树市| 葵青区| 凤山市| 土默特右旗| 自治县| 平和县| 集贤县| 衡水市| 历史| 郓城县| 古交市| 贵德县| 渝北区| 井陉县| 开封县| 志丹县| 安国市| 马鞍山市| 南华县| 丰镇市| 东阿县| 手游| 晋中市| 榆社县| 滦南县| 明星| 大渡口区| 广安市| 东至县| 杭锦后旗| 平泉县| 平乐县| 南宫市| 郸城县| 马公市| 阳新县| 山西省| 镇康县| 巴彦淖尔市| 宜丰县| 阳谷县|