MATRIX-MULTIPLICATION(A,B) if A.cols ≠ B.rows then error "incompatible dimension" else let C be a new A.rows×B.cols matrix for i ← 1 to A.rows for j ← 1 to B.cols C[i,j] ← 0 for k ← 1 to A.cols C[i,j] ← C[i,j]+A[i,k]*B[j,k] return C
MATRIX-CHAIN-MULTIPLICATION(p) n ← p.length-1 let t[1...n,1...n],s[1...n-1,2...n] be new tables
//初始化 for i ← 1 to n t[i,i] ← 0
for l ← 2 to n //l 表示矩阵链的长度 for i ← 1 to n-l+1 //i 表示起始位置 j ← l+i-1 //j 表示末尾 t[i,j] ← ∞ for k ← i to j-1 q ← t[i,k]+t[k+1,j]+p[i-1]p[k][j] if q < t[i,j] then t[i,j] ← q s[i,j] ← k return t and s
PRINT-OPTIMAL-PARENTS(s,i,j) if i = j //相等表示无法进一步分割 then print "Ai" else print "(" PRINT-OPTIMAL-PARENTS(s,i,s[i,j]) //分割点左边 PRINT-OPTIMAL-PARENTS(s,s[i.j]+1,j) //分割点右边 print ")"
template<size_t N> voidprint_matrix_chain(int s[N][N], int i, int j){ if (i == j) cout << "A" << i; else { cout << "("; print_matrix_chain(s, i, s[i][j]); print_matrix_chain(s, s[i][j] + 1, j); cout << ")"; } }
template<size_t N> longmatrix_chain(int(&p)[N]){ constexprint n = N - 1; int m[n + 1][n + 1]; int s[n][n]; for (int i = 1; i <= n; ++i) m[i][i] = 0;
for (int l = 2; l <= n; ++l) for (int i = 1; i <= n - l + 1; ++i) { int q = 0; int j = l + i - 1; m[i][j] = INT_MAX; for (int k = i; k < j; ++k) { q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) { m[i][j] = q; s[i][j] = k; } } }