麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 編程 > 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]}."

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 8x成人在线电影 | 国产精品久久久久久久久久久久午夜 | 欧美1区2区在线观看 | 日本黄色一级电影 | 人人看人人艹 | 久久精品国产亚洲7777 | 国产精品一区在线观看 | 日韩视频精品一区 | 精品成人网 | av电影观看 | 精品乱码久久久久 | 久久精品视频黄色 | v11av在线播放 | 免费a级黄色片 | 牛牛碰在线 | 视频一区二区不卡 | 亚洲午夜免费电影 | 18欧美性xxxx极品hd | chinesehd天美原创xxxx | 天天操天天碰 | 国产精品久久国产精麻豆96堂 | 久久精品超碰 | 久久精品国产精品亚洲 | 国产 一区 | 国产精品免费视频观看 | wwwxxx国产| 国产精品视频 | 精品国产91久久久久久浪潮蜜月 | 大学生一级毛片在线视频 | 欧美巨乳在线观看 | 欧美一级做 | 日韩精品中文字幕在线播放 | 国产亚洲精品久久久久久久久 | 免费淫视频 | 媚药按摩痉挛w中文字幕 | 成人国产精品久久 | 五月激情久久 | 成人性生活视频在线观看 | 日韩99 | 成人在线视频黄色 | 性明星video另类hd |