a亚洲精品_精品国产91乱码一区二区三区_亚洲精品在线免费观看视频_欧美日韩亚洲国产综合_久久久久久久久久久成人_在线区

首頁 > 編程 > Ruby > 正文

Ruby實現的最優二叉查找樹算法

2020-10-29 19:39:14
字體:
來源:轉載
供稿:網友

算法導論上的偽碼改寫而成,加上導論的課后練習第一題的解的構造函數。

復制代碼 代碼如下:

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 亚洲精品一区中文字幕乱码 | 一级免费片 | 欧美黑人xxx | 亚洲成人福利 | 久久久久久久久久久久久久久久久久久久 | 自拍偷拍第一页 | 国产高清一区二区 | 精品国产露脸精彩对白 | 精品国产精品三级精品av网址 | 日韩中文在线 | 国产天天操天天干 | 国产精品视频久久久 | 国产精品99一区二区三区 | 黄色一级片视频播放 | 午夜精品久久久久久99热软件 | 一级免费片 | 亚洲第一性理论片 | 性一交一乱一透一a级 | 日韩av一区二区在线观看 | 欧美日韩国产一区二区三区 | 蜜桃av一区二区三区 | 一区二区在线播放视频 | 久久免费高清视频 | 狠狠做深爱婷婷综合一区 | 蜜桃视频麻豆女神沈芯语免费观看 | 999在线观看精品免费不卡网站 | 少妇一区二区三区免费观看 | 欧美视频一区二区在线 | 国产精品成av人在线视午夜片 | 91精品久久久久久久久中文字幕 | 欧美国产一区二区在线观看 | 日韩色综合 | 久久精品国产免费看久久精品 | 91精品中文字幕一区二区三区 | 精品国产一区二区三区久久久蜜月 | 日韩精品 | 成人在线免费观看 | 日本不卡免费新一二三区 | www.日韩av.com | 精品国产一区二区三区久久 | 毛片一区二区三区 |