Optimal Matrix Multiplication

Given two matrices with dimensions n₁ × n₂ and n₂ × n₃, the cost of the
usual multiplication algorithm is Θ(n₁n₂n₃). For simplicity, let us
consider that the cost is exactly n₁n₂n₃.

Suppose that we must compute M₁ × … × M_(m), where every M_(i) is an
n_(i) × n_(i + 1) matrix. Since the product of matrices is associative,
we can choose the multiplication order. For example, to compute
M₁ × M₂ × M₃ × M₄, we could either choose (M₁ × M₂) × (M₃ × M₄), with
cost n₁n₂n₃ + n₃n₄n₅ + n₁n₃n₅, or either choose M₁ × ((M₂ × M₃) × M₄),
with cost n₂n₃n₄ + n₂n₄n₅ + n₁n₂n₅, or three other possible orders.

Write a program to find the minimum cost of computing M₁ × … × M_(m).

Input

Input consists of several cases, each one with m followed by the m + 1
dimensions. Assume 2 ≤ m ≤ 100 and 1 ≤ n_(i) ≤ 10⁴.

Output

For every case, print the minimum cost to compute the product of the m
matrices.

Problem information

Author: Unknown
Translator: Salvador Roura

Generation: 2026-01-25T09:58:30.977Z

© Jutge.org, 2006–2026.
https://jutge.org
