Skip to content

Commit 7563feb

Browse files
Create Matrix_chain_multiplication.c
1 parent 9e84a88 commit 7563feb

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/* Find the minimum number of scaler multiplication for chain of matrix using
2+
dynamic programming approach and find the time complexity also. Consider the given
3+
set ofmatrices A1 , A2 , A3 ,A4 with p0 = 5 , p1 = 4 , p2 = 6, p3 = 2 , p4 = 7. */
4+
5+
6+
#include<stdio.h>
7+
#include<stdlib.h>
8+
int p[100], mt[100][100], st[100][100];
9+
void print_optimal(int i , int j){
10+
if(i==j){
11+
printf("A%d ", i);
12+
}
13+
else{
14+
printf("(");
15+
print_optimal(i, st[i][j]);
16+
print_optimal(st[i][j] + 1, j);
17+
printf(")");
18+
}
19+
}
20+
int main(){
21+
int i, j, k, m,n, l, q;
22+
printf("Enter no. of elements in p: ", m);
23+
scanf("%d",&m);
24+
for(i=0;i<m;i++){
25+
printf("Enter the value P %d ", i);
26+
scanf("%d", &p[i]);
27+
printf("\n");
28+
}
29+
n = m - 1;
30+
for(i=1;i<=4;i++){
31+
mt[i][i] = 0;
32+
st[i][i] = 0;
33+
}
34+
for(l=2; l<=n;l++ ){
35+
for(i=1;i<=(n-l+1);i++){
36+
j = i+l-1;
37+
mt[i][j] = 1000000;
38+
for(k = i ; k<=(j-1); k++){
39+
q = mt[i][k] + mt[k+1][j] + (p[i-1] * p[k] * p[j]);
40+
if(q< mt[i][j]){
41+
mt[i][j] = q;
42+
st[i][j] = k;
43+
}
44+
}
45+
}
46+
}
47+
printf("\n\n M Table \n\n");
48+
for(i = 1; i<=4; i++){
49+
for(j=1;j<=4;j++){
50+
printf("%d ", mt[i][j]);
51+
}
52+
printf("\n");
53+
}
54+
printf("\n\n S Table \n\n");
55+
for(i = 1; i<=4; i++){
56+
for(j=1;j<=4;j++){
57+
printf("%d ", st[i][j]);
58+
}
59+
printf("\n");
60+
}
61+
print_optimal(1 , n);
62+
printf("\nHence minimum cost for multiplication will be = %d",
63+
mt[1][n]);
64+
}
65+
66+
67+
/*OUTPUT
68+
Enter no. of elements in p: 5
69+
Enter the value P 0 - 5
70+
Enter the value P 1 - 4
71+
Enter the value P 2 - 6
72+
Enter the value P 3 - 2
73+
Enter the value P 4 - 7
74+
75+
M Table
76+
77+
0 120 88 158
78+
0 0 48 104
79+
0 0 0 84
80+
0 0 0 0
81+
82+
S Table
83+
84+
0 1 1 3
85+
0 0 2 3
86+
0 0 0 3
87+
0 0 0 0
88+
89+
((A1 (A2 A3)) A4)
90+
Hence minimum cost for multiplication will be = 158
91+
92+
*/

0 commit comments

Comments
 (0)