1. 程式人生 > >動態規劃-矩陣鏈乘法

動態規劃-矩陣鏈乘法

system n) style ava png new value public integer

技術分享圖片

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); } }

動態規劃-矩陣鏈乘法