-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrixChainMultiplication.c
More file actions
90 lines (78 loc) · 2.1 KB
/
MatrixChainMultiplication.c
File metadata and controls
90 lines (78 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Implement the matrix chain multiplication problem using M-table & S-table to find optimal parenthesization of a matrix-chain product. Print the number of scalar multiplications required for the given input.
#include <stdio.h>
#include <limits.h>
void print_optimal_parenthesization(int s[][10], int i, int j)
{
if (i == j)
printf("A%d", i + 1);
else
{
printf("(");
print_optimal_parenthesization(s, i, s[i][j]);
print_optimal_parenthesization(s, s[i][j] + 1, j);
printf(")");
}
}
int main()
{
int n;
printf("Enter number of matrices: ");
scanf("%d", &n);
int p[10];
int m[10][10] = {0};
int s[10][10] = {0};
for (int i = 0; i < n; i++)
{
int row, col;
printf("Enter row and col size of A%d: ", i + 1);
scanf("%d %d", &row, &col);
p[i] = row;
if (i == n - 1)
p[n] = col;
}
for (int len = 2; len <= n; len++)
{
for (int i = 0; i < n - len + 1; i++)
{
int j = i + len - 1;
m[i][j] = INT_MAX;
for (int k = i; k < j; k++)
{
int q = m[i][k] + m[k + 1][j] + p[i] * p[k + 1] * p[j + 1];
if (q < m[i][j])
{
m[i][j] = q;
s[i][j] = k;
}
}
}
}
printf("\nM Table:\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i <= j)
printf("%d\t", m[i][j]);
else
printf("0\t");
}
printf("\n");
}
printf("\nS Table:\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i < j)
printf("%d\t", s[i][j]);
else
printf("0\t");
}
printf("\n");
}
printf("\nOptimal parenthesization: ");
print_optimal_parenthesization(s, 0, n - 1);
printf("\nThe optimal ordering of the given matrices requires %d scalar multiplications.\n", m[0][n - 1]);
return 0;
}