码迷,mamicode.com
首页 > 其他好文 > 详细

动态规划-矩阵链乘法

时间:2018-10-07 18:02:43      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:color   code   alt   static   The   val   top   ++   package   

技术分享图片

Java实现:

package dp;

public class MatrixChainOrder {
    public static void matrixChainOrder(int[] p, int[][] m, int[][] s) {
        int n = p.length - 1;
        for (int i = 1; i <= n ; i++) {
            m[i][i] = 0;
        }
        for (int len = 2; len <= n; len++) {
            for (int i = 1; i <= n-len+1 ; i++) {
                int j = len + i - 1;
                m[i][j] = Integer.MAX_VALUE;
                for (int k = i; k < j; k++) {
                    int q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
                    if (q < m[i][j]) {
                        m[i][j] = q;
                        s[i][j] = k;
                    }
                }
            }
        }
    }

    public static void printOptimalSolution(int[][] s, int i, int j) {
        if (i == j) {
            System.out.print("A_" + i);
        } else {
            System.out.print("(");
            printOptimalSolution(s, i, s[i][j]);
            printOptimalSolution(s, s[i][j] + 1, j);
            System.out.print(")");
        }
    }

    public static void main(String[] args) {
        int[] p ={30, 35, 15, 5, 10, 20, 25};
        int n = p.length - 1;
        int[][] m = new int[n+1][n+1];
        int[][] s = new int[n+1][n+1];
        matrixChainOrder(p, m, s);
        System.out.println("The optimal value:" + m[1][n]);
        System.out.print("The optimal solution is:\n\t");
        printOptimalSolution(s, 1, n);
    }
}

 

动态规划-矩阵链乘法

标签:color   code   alt   static   The   val   top   ++   package   

原文地址:https://www.cnblogs.com/skyke/p/9750643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!