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

matrix_chain_order

时间:2017-06-22 00:15:36      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:cat   ret   ati   value   matrix   n+1   sort   seq   merge   

to calculate the min step of multiplicate some matixs

 1 package dynamic_programming;
 2 
 3 public class matrix_chain_order { //input is a sequence p = p0,p1..pn,where p.length = n+1  (matrix n is pn-1pn)
 4     int[] p;
 5     int[][] cost;
 6      public matrix_chain_order(int[] a){
 7          p = a;
 8      }
 9      public int order(){
10         int q = 0;
11         int n = p.length -1;
12         cost = new int[n][n];
13         for(int i = 0;i<= n-1;i++){
14             cost[i][i] = 0;
15         }
16         for(int l = 2;l<n;l++){  //the chain length,like merge sort
17             for(int i=0;i<n-l;i++){
18                 int j = i+l -1;
19                 cost[i][j] =Integer.MAX_VALUE;
20                 for(int k = i;k <=j -1;k++){
21                     q = cost[i][k] + cost[k+1][j] + p[i-1]*p[k]*p[j];
22                     if(q < cost[i][j]){
23                         cost[i][j] = q; //remeber the best step of i to j
24                     }
25                 }
26             }
27         }
28         return cost[n-1][n-1];
29      }
30      
31 
32 }

 

matrix_chain_order

标签:cat   ret   ati   value   matrix   n+1   sort   seq   merge   

原文地址:http://www.cnblogs.com/wujunde/p/7062083.html

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