Matrix-chain Multiplication

Posted zjsyzmx0527

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Matrix-chain Multiplication相关的知识,希望对你有一定的参考价值。

Source

https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/all/ALDS1_10_B

 

Description

Time Limit : 1 sec , Memory Limit : 131072 KB

Matrix-chain Multiplication

The goal of the matrix-chain multiplication problem is to find the most efficient way to multiply given nn matrices M1,M2,M3,...,MnM1,M2,M3,...,Mn.

Write a program which reads dimensions of MiMi, and finds the minimum number of scalar multiplications to compute the maxrix-chain multiplication M1M2...MnM1M2...Mn.

Input

In the first line, an integer nn is given. In the following nn lines, the dimension of matrix MiMi (i=1...ni=1...n) is given by two integers rr and cc which respectively represents the number of rows and columns of MiMi.

Output

Print the minimum number of scalar multiplication in a line.

Constraints

  • 1n1001≤n≤100
  • 1r,c1001≤r,c≤100

Sample Input 1

6
30 35
35 15
15 5
5 10
10 20
20 25

Sample Output 1

15125

Code
 1 #include<stdio.h>
 2 #include<string.h>
 3 #define M 103
 4 #define Min 1000000000
 5 void Matrix_Chain_Order(int p[],int n);
 6 int main()
 7 {
 8     int n;
 9     while(scanf("%d",&n) == 1){
10         int p[M];
11         memset(p,0,M);
12         int i;
13         for(i = 0;i < n;i++)
14             scanf("%d%d",&p[i],&p[i+1]);
15         Matrix_Chain_Order(p,n);
16     }
17 
18     return 0;
19 }
20 
21 void Matrix_Chain_Order(int p[],int n)
22 {
23     int m[n+1][n+1],s[n+1][n+1];
24     //边界条件
25     int i,j;
26     for(i = 1;i <= n;i++)
27         m[i][i] = 0;
28     //计算每个子问题m[i,j]的解
29     int l;
30     for(l = 2;l <= n;l++){
31         for(i = 1;i <= n-l+1;i++){
32             j = i + l - 1;
33             m[i][j] = Min;
34             int k;
35             for(k = i;k <= j-1;k++){
36                 int val;
37                 val = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
38                 if(m[i][j] > val){
39                     m[i][j] = val;
40                     s[i][j] = k;
41                 }
42             }
43         }
44     }
45     printf("%d
",m[1][n]);
46 }

 



以上是关于Matrix-chain Multiplication的主要内容,如果未能解决你的问题,请参考以下文章