import sys
def matrix_chain_order(p):
"""
Computes the minimum cost for matrix chain multiplication using dynamic programming.
Args:
p (list): List of matrix dimensions, e.g., [10, 20, 30] for matrices A1(10x20), A2(20x30).
Returns:
tuple: (m, s) where m[i][j] is min cost for matrices i to j, s[i][j] is optimal split point.
"""
n = len(p) - 1 # Number of matrices
if n < 1:
raise ValueError("At least one matrix required (at least two dimensions).")
# Initialize DP tables: m for costs, s for splits
m = [[0] * (n + 1) for _ in range(n + 1)]
s = [[0] * (n + 1) for _ in range(n + 1)]
# Fill tables for chain lengths from 2 to n
for chain_len in range(2, n + 1):
for i in range(1, n - chain_len + 2):
j = i + chain_len - 1
m[i][j] = sys.maxsize # Initialize to infinity
# Try all possible splits k
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
def print_optimal_parens(s, i, j):
"""
Recursively constructs the optimal parenthesization string.
Args:
s (list): Split table from matrix_chain_order.
i, j (int): Range of matrices from i to j (1-indexed).
Returns:
str: Parenthesized expression, e.g., "((A1 A2) A3)".
"""
if i == j:
return f"A{i}"
else:
k = s[i][j]
left = print_optimal_parens(s, i, k)
right = print_optimal_parens(s, k + 1, j)
return f"({left} {right})"
# Example usage
if __name__ == "__main__":
# Dimensions for matrices: A1(10x30), A2(30x5), A3(5x60)
p = [10, 30, 5, 60]
m, s = matrix_chain_order(p)
n = len(p) - 1
min_cost = m[1][n]
parens = print_optimal_parens(s, 1, n)
print(f"Dimensions: {p}")
print(f"Minimum cost: {min_cost}")
print(f"Optimal parenthesization: {parens}")
# Output:
# Dimensions: [10, 30, 5, 60]
# Minimum cost: 4500
# Optimal parenthesization: ((A1 A2) A3)
Explanation
- Time Complexity: O(n³), where n is the number of matrices.
- Space Complexity: O(n²) for the DP tables.
- Indices: Matrices are 1-indexed (A₁ to Aₙ); dimensions are 0-indexed in
p.
- How it works:
m[i][j] stores the min cost to multiply matrices i to j.
s[i][j] stores the optimal k where the split occurs.
- Bottom-up DP: Iterate over increasing chain lengths, trying all splits.
- Customization: Call
matrix_chain_order(dims) for costs/splits, then print_optimal_parens(s, 1, n) for the parenthesization string.
This implementation is efficient, readable, and includes a testable example. For larger inputs, it scales cubically as expected.