|
 |
 |
 |
 |
 |
 |
 |
 |
 |
 |
| • |
Can’t
afford to keep
|
|
|
|
computing
best(i,j) over and
|
|
|
over
for the same values
|
|
|
| • |
So we
store it in an array:
|
|
|
C[i,j]
is the least cost for
|
|
|
|
multiplying
M[i]...M[j]
|
|
|
| • |
Just
be careful that each
|
|
|
|
position
in C[i,j] is filled
|
|
|
before
it’s used
|
|
|
|
 |
 |
 |
 |
 |
 |
 |
 |
 |
 |
LeastCostMatrixMult()
{
|
|
|
for i =
1 to n do C[i,i] = 0;
|
|
|
for
size = 1 to n-1 do
|
|
|
for i = 1 to n-size do
|
|
|
min = infinity; j = i+size;
|
|
|
for k = i to j-1 do
|
|
|
cost = C[i,k] + C[k+1,j]
|
|
|
+ r[i]*r[k+1]*r[j+1];
|
|
|
if (cost < min) min = cost;
|
|
C[i,j] = min;
|
|
|
return C[1,n].
|
|
|
|