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

來源:互聯網
上載者:User

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

   這篇文章主要介紹了Ruby實現的最優二叉尋找樹演算法,本文直接給出實現代碼,需要的朋友可以參考下

  演算法導論上的偽碼改寫而成,加上導論的課後練習第一題的解的建構函式。

  代碼如下:

  #encoding: utf-8

  =begin

  author: xu jin

  date: Nov 11, 2012

  Optimal Binary Search Tree

  to find by using EditDistance algorithm

  refer to <>

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.