Optimal Matrix Multiplication P11455


Statement
 

pdf   zip

Given two matrices with dimensions n1×n2n_1 \times n_2 and n2×n3n_2 \times n_3, the cost of the usual multiplication algorithm is Θ(n1n2n3)\Theta(n_1 n_2 n_3). For simplicity, let us consider that the cost is exactly n1n2n3n_1 n_2 n_3.

Suppose that we must compute M1××MmM_1 \times \dots \times M_m, where every MiM_i is an ni×ni+1n_i \times n_{i+1} matrix. Since the product of matrices is associative, we can choose the multiplication order. For example, to compute M1×M2×M3×M4M_1 \times M_2 \times M_3 \times M_4, we could either choose (M1×M2)×(M3×M4)(M_1 \times M_2) \times (M_3 \times M_4), with cost n1n2n3+n3n4n5+n1n3n5n_1 n_2 n_3 + n_3 n_4 n_5 + n_1 n_3 n_5, or either choose M1×((M2×M3)×M4)M_1 \times ((M_2 \times M_3) \times M_4), with cost n2n3n4+n2n4n5+n1n2n5n_2 n_3 n_4 + n_2 n_4 n_5 + n_1 n_2 n_5, or three other possible orders.

Write a program to find the minimum cost of computing M1××MmM_1 \times \dots \times M_m.

Input

Input consists of several cases, each one with mm followed by the m+1m + 1 dimensions. Assume 2m1002 \le m \le 100 and 1ni1041 \le n_i \le 10^4.

Output

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

Public test cases
  • Input

    2   1 2 3
    3   10 20 30 40
    10  9000 4000 3500 8000 2000 7500 6000 1000 8500 5500 7000
    

    Output

    6
    18000
    302250000000
    
  • Information
    Author
    Salvador Roura
    Language
    English
    Translator
    Salvador Roura
    Original language
    Catalan
    Other languages
    Catalan
    Official solutions
    C++
    User solutions
    C++