时间:2021-05-22
动态规划解决矩阵连乘问题,随机产生矩阵序列,输出形如((A1(A2A3))(A4A5))的结果。
代码:
#encoding: utf-8=beginauthor: xu jin, 4100213date: Oct 28, 2012MatrixChainto find an optimum order by using MatrixChain algorithmexample output:The given array is:[30, 35, 15, 5, 10, 20, 25]The optimum order is:((A1(A2A3))((A4A5)A6))The total number of multiplications is: 15125The random array is:[5, 8, 8, 2, 5, 9]The optimum order is:((A1(A2A3))(A4A5))The total number of multiplications is: 388 =endINFINTIY = 1 / 0.0p = [30, 35, 15, 5, 10, 20, 25]m, s = Array.new(p.size){Array.new(p.size)}, Array.new(p.size){Array.new(p.size)}def matrix_chain_order(p, m, s) n = p.size - 1 (1..n).each{|i| m[i][i] = 0} for r in (2..n) do for i in (1..n - r + 1) do j = r + i - 1 m[i][j] = INFINTIY for k in (i...j) do q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j] m[i][j], s[i][j] = q, k if(q < m[i][j]) end end endend def print_optimal_parens(s, i, j) if(i == j) then print "A" + i.to_s else print "(" print_optimal_parens(s, i, s[i][j]) print_optimal_parens(s, s[i][j] + 1, j) print ")" endenddef process(p, m, s) matrix_chain_order(p, m, s) print "The optimum order is:" print_optimal_parens(s, 1, p.size - 1) printf("\nThe total number of multiplications is: %d\n\n", m[1][p.size - 1])endputs "The given array is:" + p.to_sprocess(p, m, s)#produce a random arrayp = Array.newx = rand(10)(0..x).each{|index| p[index] = rand(10) + 1}puts "The random array is:" + p.to_sm, s = Array.new(p.size){Array.new(p.size)}, Array.new(p.size){Array.new(p.size)}process(p, m, s)声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了Java矩阵连乘问题(动态规划)算法。分享给大家供大家参考,具体如下:问题描述:给定n个矩阵:A1,A2,...,An,其中Ai与Ai+1是可乘的
本文实例讲述了动态规划之矩阵连乘问题Python实现方法。分享给大家供大家参考,具体如下:给定n个矩阵{A1,A2,…,An},其中Ai与Ai+1是可乘的,i=
本文实例讲述了java实现的n*n矩阵求值及求逆矩阵算法。分享给大家供大家参考,具体如下:先来看看运行结果:java版的写出来了,用的跟c语言相同的算法,然后看
刚学Ruby,正巧算法老师鼓励用不熟悉的语言来写算法,我就用Ruby吧~~话说Ruby可真是超厉害,好多凭直觉的方法都可以用。。。。。无限膜拜中。。。。期间我遇
本文实例讲述了Java实现的求逆矩阵算法。分享给大家供大家参考,具体如下:packagedemo;publicclassMatrixInverse{public