1. Understand the Goal: The user wants a program that implements the Matrix Chain Multiplication (MCM) problem. This is a classic dynamic programming problem.
Determine the Scope and Language:
Language: Python is generally the most accessible for algorithms, but C++ or Java are also common. I'll provide the solution in Python because of its readability, but I might offer a brief explanation that the logic applies elsewhere. Let's stick to Python as the primary implementation.
Functionality: The program needs to:
Take a sequence of matrix dimensions (e.g., [10, 30, 5, 60] representing matrices 10×30, 30×5, and 5×60).
Calculate the minimum number of scalar multiplications required to multiply the chain.
(Optional but good) Show the optimal parenthesization (e.g., ((A1(A2A3))A).
Approach: There are two main ways to solve MCM using Dynamic Programming:
Recursive (Top-Down with Memoization): Good for understanding the logic, but maybe less standard for a "program" request.
Iterative (Bottom-Up / Tabulation): The standard textbook approach. It fills a table m[i,j] where i≤j.
Algorithm Design (Bottom-Up):
Input: An array p of size n+1, where matrix Ai has dimensions p[i−.
Reconstructing the Solution:
Need a recursive function print_optimal_parens(s, i, j) that prints (A + left part + x + right part + ). Or just names like ((M1 x M2) x M3).
Drafting the Code (Mental or Scratchpad):
python
def matrix_chain_order(p):
n = len(p) - 1
m = [[0] * (n + 1) for _ in range(n + 1)]
s = [[0] * (n + 1) for _ in range(n + 1)] # For parenthesization
# L is chain length
for L in range(2, n + 1):
for i in range(1, n - L + 2):
j = i + L - 1
m[i][j] = float('inf')
for k in range(i, j):
cost = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]
if cost < m[i][j]:
m[i][j] = cost
s[i][j] = k
return m, s
# Helper to print parentheses
def print_parens(s, i, j):
if i == j:
return f"M{i}"
else:
return f"({print_parens(s, i, s[i][j])} x {print_parens(s, s[i][j] + 1, j)})"
Refining the User Experience:
The code should be self-contained.
Include an example usage block (if __name__ == "__main__":).
Add comments explaining the Time Complexity (O(n3)) and Space Complexity (O(n2)).
Alternative (Recursive with Memoization):
Sometimes users prefer the recursive approach as it maps directly to the math. I will stick to the iterative approach as it's the standard "solution" to MCM, but I might briefly mention the recursive nature in the comments.
Final Code Structure:
This looks solid. I will structure the response with a brief introduction, the Python code, and an explanation of how it works.
Here is a complete implementation of the Matrix Chain Multiplication problem using Dynamic Programming in Python.
This solution includes:
matrix_chain_order: A function that calculates the minimum number of multiplications needed and stores the optimal split points.
print_optimal_parens: A helper function to reconstruct and print the parentheses for the optimal multiplication order.
Example Usage: A sample array representing matrix dimensions to demonstrate the code.
The Python Program
python
import sys
def matrix_chain_order(p):
"""
Solves the Matrix Chain Multiplication problem using Dynamic Programming.
Args:
p (list): A list of integers where matrix i has dimension p[i] x p[i+1].
Returns:
m (list of lists): Table containing minimum multiplication costs.
s (list of lists): Table containing split points for reconstruction.
"""
n = len(p) - 1 # Number of matrices
# Initialize tables
# m[i][j] = Minimum multiplications needed for matrices A[i]...A[j]
# s[i][j] = The index k at which the product is split
m = [[0 for _ in range(n)] for _ in range(n)]
s = [[0 for _ in range(n)] for _ in range(n)]
# L is the chain length. We start with length 2 (pair of matrices)
# and go up to the full chain length n.
for L in range(2, n + 1):
for i in range(n - L + 1):
j = i + L - 1
m[i][j] = sys.maxsize # Set to infinity initially
# Try every possible split point k between i and j
for k in range(i, j):
# Cost formula:
# Cost of left chain + Cost of right chain +
# Cost of multiplying the two resulting matrices
# Dimensions: (p[i] x p[k]) and (p[k] x p[j])
q = (m[i][k] + m[k+1][j] + p[i] * p[k+1] * p[j+1])
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 parenthesis arrangement.
"""
if i == j:
return f"M{i+1}" # Using 1-based indexing for display
else:
k = s[i][j]
left = print_optimal_parens(s, i, k)
right = print_optimal_parens(s, k + 1, j)
return f"({left} x {right})"
# --- Main Execution ---
if __name__ == "__main__":
# Example Input: Dimensions of matrices
# Matrix 1: 10 x 20
# Matrix 2: 20 x 30
# Matrix 3: 30 x 40
# Matrix 4: 40 x 30
dimensions = [10, 20, 30, 40, 30]
print(f"Matrix Dimensions: {dimensions}")
# Compute optimal order
cost_table, split_table = matrix_chain_order(dimensions)
# Get results
num_matrices = len(dimensions) - 1
min_cost = cost_table[0][num_matrices-1]
optimal_order = print_optimal_parens(split_table, 0, num_matrices-1)
print(f"\nMinimum number of multiplications needed: {min_cost}")
print(f"Optimal Parenthesization: {optimal_order}")
How it Works
Input p:
The input is an array where the i-th matrix has dimensions p[i]×p[i+1].
For example, [10, 20, 30] represents two matrices: 10×20 and .
Example Output
For the input [10, 20, 30, 40, 30] (4 matrices), the output is:
text
Matrix Dimensions: [10, 20, 30, 40, 30]
Minimum number of multiplications needed: 30000
Optimal Parenthesization: ((M1 x (M2 x M3)) x M4)
4
)
1
]
×
p[i]
Data Structures:
dp[i][j]: Stores the minimum cost of multiplying matrices Ai…Aj.
s[i][j]: Stores the index of the split (the k) that gave the optimal cost, used for reconstructing the parentheses.
Logic:
dp[i][i] = 0 for all i (cost of multiplying one matrix is 0).
If Cost < dp[i][j], update dp[i][j] and record s[i][j] = k.
Class-based or Function-based? Function-based is simpler for scripts.
Input: list of integers.
Output: Print min operations and the parenthesized string.
Writing the Explanation:
Briefly explain the problem statement (finding optimal split points to minimize scalar multiplications).
Explain the inputs (dimension array).
Present the Python code.
Show the output for a sample input.
Self-Correction/Edge Cases:
What if p has fewer than 2 elements? n should be at least 1. I should probably add a check or just assume valid input for an algorithmic demo. I'll assume valid input len(p) >= 2.
Indexing: Python is 0-indexed, but the algorithm is often described 1-indexed. I can implement it using 0-indexing in Python to be more "Pythonic", or stick to the standard 1-based logic using list offsets. The 1-based logic (ignoring index 0) is easier to map to textbooks (like CLRS), but 0-based is cleaner in Python.
Let's write 0-based logic to be natural in Python.
n = number of matrices = len(p) - 1.
dp[i][j] refers to matrices from index i to j.
Dimensions for matrix i are p[i] (rows) and p[i+1] (cols).
Range for L: 2 to n.
Range for i: 0 to n - L.
j: i + L - 1.
k: i to j - 1.
Cost: p[i] * p[k+1] * p[j+1].
Final Code Polish:
Let's write the 0-indexed version to avoid confusion for Python users.
python
import sys
def matrix_chain_order(p):
n = len(p) # n is number of matrices + 1
# Actually, let's make n the count of matrices
n_matrices = len(p) - 1
# dp[i][j] = Minimum scalar multiplications needed to compute matrix A[i]...A[j]
# Initialize with 0 for i == j
dp = [[0 for x in range(n_matrices)] for y in range(n_matrices)]
# parenthesis[i][j] = Optimal split point k
parenthesis = [[0 for x in range(n_matrices)] for y in range(n_matrices)]
# L is chain length.
for L in range(2, n_matrices + 1):
for i in range(n_matrices - L + 1):
j = i + L - 1
dp[i][j] = sys.maxsize
for k in range(i, j):
# q = cost/scalar multiplications
# cost = cost of left split + cost of right split + cost of multiplying resulting two matrices
# Dimensions:
# A[i] is p[i] x p[i+1]
# A[k] is p[k] x p[k+1]
# A[j] is p[j] x p[j+1]
# Result of A[i..k] is p[i] x p[k+1]
# Result of A[k+1..j] is p[k+1] x p[j+1]
q = dp[i][k] + dp[k+1][j] + p[i] * p[k+1] * p[j+1]
if q < dp[i][j]:
dp[i][j] = q
parenthesis[i][j] = k
return dp[0][n_matrices-1], parenthesis
def print_optimal_parens(s, i, j):
if i == j:
return f"M{i+1}" # 1-based naming for display
else:
return f"({print_optimal_parens(s, i, s[i][j])} x {print_optimal_parens(s, s[i][j] + 1, j)})"
Review against User Request: "Write a program that implements the matrix chain multiplication problem."
The code covers the logic, finding the minimum cost.
It includes the parenthesization part, which is usually expected in this specific problem to prove it works.
The explanation will clarify the dynamic programming approach.
20×30
Dynamic Programming Table m:
We create a 2D table m[][] where m[i][j] stores the minimum computation cost to multiply the chain from matrix i to matrix j.
Cost is 0 when i=j (single matrix).
For larger chains, we calculate the cost by splitting the chain at every possible point k.
Recurrence Relation:
To find the minimum cost for the range [i,j], we iterate through k (from i to j−1):
Cost=m[i][k]+m[k+1][j]+p[i]×p[k+1]×p[
The term p[i]×p[k+1]×p[j+1] represents the cost of multiplying the resulting matrix from the left side (i…k) with the resulting matrix from the right side (k+1…j).
Split Table s:
Whenever we find a new minimum cost, we store the split index k in table s[][]. This allows us to reconstruct the solution (print the parentheses) later.