Beruflich Dokumente
Kultur Dokumente
Given a chain of n matrices A1 , A2 , ..., An where for i = 1, 2, ..., n, matrix Ai has dimensions pi1 pi , fully parenthesize the product A1 A2 . . . An to minimizes the number of scalar multiplications. A product of matrices is fully parenthesized if it is either a single matrix or the product of two fully parenthesized matrix products which are surrounded by parentheses.
n = p.length; let n[1..n, 1..n] be a new table; let s[1..n-1, 2..n] be a new table; for i = 1 to n do n[i, i] = 0; end for d = 1 to n-1 do for i = 1 to n-1 do j = i + d; n[i, j] = ; for k = i to j-1 do if n[i, j ] > n[i, k ] + n[k + 1, j ] + p[i 1]p[k ]p[j ] then n[i, j] = n[i, k] + n[k+1, j] + p[i-1]p[k]p[j]; s[i, j] = k; end end end end return n and s;
The space complexity of this procedure is clearly O(n2 ), for m and s require O(n2 ) space. The time complexity of this procedure is O(n3 ), for there are three-level nested loops, and each of them iterates at most n times.
if i == j then return A[i]; else k = s[i, j]; X = MCM(s, i, k); Y = MCM(s, k+1, j); return XY end