-
Notifications
You must be signed in to change notification settings - Fork 0
/
MCM_Mem.cpp
149 lines (118 loc) · 2.13 KB
/
MCM_Mem.cpp
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include <iostream>
#include <sstream>
using namespace std;
class Matrix{
private:
string name = "A";
int x, y;
public:
void setMatrix(int i, int j, int matNum)
{
this->x = i;
this->y = j;
// converting int to string
string sNum;
stringstream ss;
ss<<matNum;
ss>>sNum;
name += sNum;
}
void printMatrix()
{
cout<<"Name: "<<name<<"\tOrder: "<<x<<"x"<<y<<"\n";
}
};
int MCM(int i, int j);
void createTable(int numMatrices);
void printTable(int numMatrices);
int d[] = {3,2,5,6,3};
int **M, **kTable;
int main()
{
int nD = sizeof(d)/sizeof(int); // number of orders
int matCount = nD-1; // number of matrices
Matrix arrMat[matCount+1];
for(int i=1; i<=matCount; i++)
{
arrMat[i].setMatrix(d[i-1], d[i], i);
arrMat[i].printMatrix();
}
createTable(matCount);
cout<<"\n\nMinimum Cost Of Multiplying Matrices: "<<MCM(1, matCount)<<"\n\n";
printTable(matCount);
}
int MCM(int i, int j)
{
if(i == j)
{
return M[i][j] = 0;
}
int min = INT_MAX, kVal;
for(int k=i; k<j; k++)
{
if(M[i][k] == -1)
{
M[i][k] = MCM(i, k);
}
if(M[k+1][j] == -1)
{
M[k+1][j] = MCM(k+1, j);
}
int x = M[i][k] + M[k+1][j] + d[i-1] * d[k] * d[j];
if(x < min)
{
kVal = k;
min = x;
}
}
kTable[i][j] = kVal;
return M[i][j] = min;
}
void createTable(int numMatrices)
{
M = new int*[numMatrices+1];
for(int i=0; i<numMatrices+1; i++)
{
M[i] = new int[numMatrices+1];
}
for(int i=1; i<=numMatrices; i++)
{
for(int j=1; j<=numMatrices; j++)
{
M[i][j] = -1;
}
}
kTable = new int*[numMatrices+1];
for(int i=0; i<numMatrices+1; i++)
{
kTable[i] = new int[numMatrices+1];
}
for(int i=1; i<=numMatrices; i++)
{
for(int j=1; j<=numMatrices; j++)
{
kTable[i][j] = 0;
}
}
}
void printTable(int numMatrices)
{
cout<<"\n\nMemoization Table\n\n";
for(int i=1; i<=numMatrices; i++)
{
for(int j=1; j<=numMatrices; j++)
{
cout<<M[i][j]<<"\t";
}
cout<<"\n\n";
}
cout<<"\n\nk Table\n\n";
for(int i=1; i<=numMatrices; i++)
{
for(int j=1; j<=numMatrices; j++)
{
cout<<kTable[i][j]<<"\t";
}
cout<<"\n\n";
}
}