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

Matrix-chain Multiplication

时间:2018-11-02 01:58:42      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:compute   can   NPU   nes   cti   tag   mat   limit   body   

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

 

Matrix-chain Multiplication

标签:compute   can   NPU   nes   cti   tag   mat   limit   body   

原文地址:https://www.cnblogs.com/zjsyzmx0527/p/9893378.html

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