256 OTHER ALGORITHMIC TECHNIQUES
a matrix called trace that is used by the next algorithm to actually determine
the order of the multiplication that will produce this minimum cost.
for i = 1 to N do
costi,i = 0
end for
for i = 1 to N-1 do
for j = 1 to N-i do
loc = i + j
tempCost = ∞
for k = i to loc-1 do
if tempCost > costi,k + costk+1,loc + si*sk*sloc then
tempCost = costi,k + costk+1,loc + si*sk*sloc
tempTrace = kMultiplication Order Resulting Matrix Size Total Cost in MultiplicationsM 1 ∗ M 2
M 2 ∗ M 3
M 3 ∗ M 4(M 1 ∗ M 2 )∗ M 3((M 1 ∗ M 2 )∗ M 3 )∗ M 4
(M 1 ∗ (M 2 ∗ M 3 ))∗ M 4M 1 ∗ ((M 2 ∗ M 3 )∗ M 4 )(M 1 ∗ M 2 )∗ (M 3 ∗ M 4 )M 1 ∗ (M 2 ∗ (M 3 ∗ M 4 ))(M 2 ∗ M 3 )∗ M 4M 1 ∗ (M 2 ∗ M 3 )M 2 ∗ (M 3 ∗ M 4 )20 × 3520 × 25
20 × 2520 × 2520 × 25
20 × 2520 × 420 × 435 × 255 × 255 × 255 × 43500700
35003500 + 2800 = 6300
700 + 400 = 1100700 + 500 = 12003500 + 4375 = 78756300 + 2000 = 83001100 + 2000 = 3100
1200 + 2500 = 37007875 + 2500 = 10,3753500 + 3500 + 17,500 = 24,500■FIGURE 9.7
The amount of
work needed to
multiply four
matrices in
different orders