I've started by clearly defining the problem: efficiently multiplying a chain of matrices. The goal is set: determine the most streamlined method. I'm focusing on the input, which is the array of dimensions, and its impact on the computational complexity.
Calculating Computational Cost
I'm now formulating the recurrence relation. My base case, where i equals j, is straightforward. Then I will determine the recursive step and the cost of combining subproblems, working from left to right. I'm also considering the implications of the matrix dimensions.
Developing DP Algorithm
Now, I'm fleshing out the dynamic programming algorithm. Focusing on the crucial steps: setting up the table m, iterating based on chain length, and pinpointing the split point, k, which gives us the minimum cost. I am considering storing the optimal split points to reconstruct the parenthesization later on.
Developing Solution and Code
I'm now deep in the implementation. I've formulated the core dynamic programming steps and the recurrence relation. I'm focusing on the matrix and split point tables. I've designed the bottom-up approach and written a Python implementation, with a base cost calculation. Next, I plan to augment it with parenthesization reconstruction.
Constructing Parenthesizations
Now, I'm focusing on the final step: reconstructing the optimal parenthesization. By incorporating the 's' table during the dynamic programming phase, I'll use it to recursively generate the parenthesization string. I'll translate the split points into a series of nested parenthetical expressions, resulting in a fully parenthesized matrix chain.
Here is a complete implementation of the Matrix Chain Multiplication algorithm using Dynamic Programming in Python.
This solution includes the calculation of the minimum number of operations and a function to reconstruct the optimal parenthesization structure.
The Logic
Given a sequence of matrices A1,A2,…,An where matrix Ai has dimensions p[i−1]×p[i].
Let m[i][j] be the minimum number of scalar multiplications needed to compute the matrix Ai…j.
Recurrence Relation:m[i][j]=mini≤k<
Base Case:m[i][i]=0 (Cost is zero when there is only one matrix).
Implementation
python
import sys
def matrix_chain_order(p):
"""
Computes the optimal order of matrix chain multiplication.
Args:
p: A list of integers representing dimensions.
Example: [10, 20, 30] represents two matrices: 10x20 and 20x30.
Returns:
m: The cost table (m[1][n] contains the min scalar multiplications).
s: The split table (used to reconstruct the solution).
"""
n = len(p) - 1 # Number of matrices
# m[i][j] stores the minimum number of multiplications for chain A_i...A_j
# We use size n + 1 to allow 1-based indexing for convenience
m = [[0] * (n + 1) for _ in range(n + 1)]
# s[i][j] stores the index k at which the optimal split occurs
s = [[0] * (n + 1) for _ in range(n + 1)]
# L is the chain length. We solve for chains of length 2 up to n.
# L=1 is implicitly 0 (initialized in m)
for L in range(2, n + 1):
# i is the starting index of the chain
for i in range(1, n - L + 2):
j = i + L - 1 # j is the ending index of the chain
m[i][j] = float('inf')
# Try every possible split point k between i and j
for k in range(i, j):
# Cost = cost(left) + cost(right) + cost(combine)
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
return m, s
def print_optimal_parens(s, i, j):
"""
Recursively prints the optimal parenthesization.
"""
if i == j:
print(f"A{i}", end="")
else:
print("(", end="")
print_optimal_parens(s, i, s[i][j])
print_optimal_parens(s, s[i][j] + 1, j)
print(")", end="")
# --- Example Usage ---
if __name__ == "__main__":
# Example Dimensions:
# A1: 30x35
# A2: 35x15
# A3: 15x5
# A4: 5x10
# A5: 10x20
# A6: 20x25
dims = [30, 35, 15, 5, 10, 20, 25]
print(f"Dimension Array: {dims}")
cost_matrix, split_matrix = matrix_chain_order(dims)
n = len(dims) - 1
print(f"Minimum Scalar Multiplications needed: {cost_matrix[1][n]}")
print("Optimal Parenthesization: ", end="")
print_optimal_parens(split_matrix, 1, n)
print()
Complexity Analysis
Time Complexity: O(n3)
We have three nested loops is the algorithm.
The outer loops determine the sub-chain states (O(n2) states).
The inner loop iterates through split point k, taking linear time relative to the chain length.
How it works (Step-by-Step Example)
If input is [10, 20, 30]:
This represents Matrix A (10×20) and Matrix B (20×30).