1
+ #include <stdio.h>
2
+ #define inf 99999
3
+ int n ;
4
+ int Chain_multi (int P [], int s [n - 1 ][n - 1 ], int n ) // P is the array of dimensions
5
+ {
6
+ int m [n ][n ];
7
+
8
+ int i , j , k , L , q ;
9
+
10
+ // cost is zero when multiplying one matrix.
11
+ for (i = 1 ; i < n ; i ++ )
12
+ m [i ][i ] = 0 ;
13
+
14
+ // L is chain length.
15
+ for (L = 2 ; L < n ; L ++ ) {
16
+ for (i = 1 ; i < n - L + 1 ; i ++ )
17
+ {
18
+ j = i + L - 1 ;
19
+ m [i ][j ] = inf ;
20
+
21
+ for (k = i ; k <= j - 1 ; k ++ )
22
+ {
23
+ // q = cost/scalar multiplications
24
+ q = m [i ][k ] + m [k + 1 ][j ] + P [i - 1 ] * P [k ] * P [j ];
25
+ if (q < m [i ][j ])
26
+ m [i ][j ] = q ;
27
+ s [i ][j ] = k ;
28
+ }
29
+ }
30
+ }
31
+
32
+ return m [1 ][n - 1 ];
33
+ // return m;
34
+ }
35
+
36
+ void print_Optimal_parens (int s [n - 1 ][n - 1 ], int i , int j ){
37
+ if (i == j )
38
+ printf ("A%d" , i );
39
+ else {
40
+ printf ("(" );
41
+ print_Optimal_parens (s , i , s [i ][j ]);
42
+ print_Optimal_parens (s , s [i ][j ]+ 1 , j );
43
+ printf (")" );
44
+ }
45
+ }
46
+
47
+ int main (){
48
+ int n , i , dim1 , dim2 ;
49
+ printf ("Enter number of matrices: " );
50
+ scanf ("%d" , & n );
51
+ int P [n + 1 ];
52
+ printf ("Enter dimensions of the matrices\n" );
53
+ for (i = 0 ;i < n ;i ++ ){
54
+ printf ("Matrix A%d: " , i + 1 );
55
+ scanf ("%d %d" , dim1 , dim2 );
56
+ /*if(!P[i]) //prevents overriding
57
+ {
58
+ P[i] = dim1;
59
+ P[i+1] = dim2;
60
+ }
61
+ else
62
+ P[i+1] = dim2;*/
63
+ P [i ] = dim1 ;
64
+ P [i + 1 ] = dim2 ;
65
+ }
66
+
67
+ int s [n - 1 ][n - 1 ];
68
+ int m = Chain_multi (P , s , n );
69
+ printf ("\nMinimum number of multiplications = %d\n" , m );
70
+ print_Optimal_parens (s , 1 , n );
71
+ return 0 ;
72
+ }
0 commit comments