1. 程式人生 > >Matrix-chain Multiplication

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 

n">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 

n">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\n",m[1][n]);
46 }