Under construction

Still being built. Things may change

Matrix chain multiplication order

Time limit1sMemory limit256 MB

Summary
Find the parenthesization of N given matrices that minimizes the total number of scalar multiplications.
Level

Medium4 of 10

Topics
Dynamic programming, Matrix
Solved
No attempts yet

Problem

Multiplying an N×MN \times M matrix AA by an M×KM \times K matrix BB takes N×M×KN \times M \times K scalar multiplications. When several matrices are multiplied, the total number of scalar multiplications depends on the order in which the products are taken.

Suppose AA is 5×35 \times 3, BB is 3×23 \times 2, and CC is 2×62 \times 6. There are two orders for computing the product ABCABC.

  • Multiplying ABAB first and then multiplying by CC costs 5×3×2+5×2×6=30+60=905 \times 3 \times 2 + 5 \times 2 \times 6 = 30 + 60 = 90 scalar multiplications for (AB)C(AB)C.
  • Multiplying BCBC first and then multiplying AA on the left costs 3×2×6+5×3×6=36+90=1263 \times 2 \times 6 + 5 \times 3 \times 6 = 36 + 90 = 126 scalar multiplications for A(BC)A(BC).

The resulting matrix is the same, but the count of operations changes with the order.

Given the sizes of NN matrices, write a program that finds the minimum number of scalar multiplications needed to multiply all of them. You must not reorder the matrices given in the input.

Input

The first line contains the number of matrices NN. (1≤N≤5001 \le N \le 500)

Each of the next NN lines contains the size rr and cc of one matrix, in the order the matrices are multiplied. (1≤r,c≤5001 \le r, c \le 500)

The input always describes sizes that can be multiplied in the given order. That is, the column count of the ii-th matrix equals the row count of the (i+1)(i+1)-th matrix.

Output

Print the minimum number of scalar multiplications needed to multiply all the given matrices. The answer is at most 231−12^{31}-1. Even the worst order takes at most 231−12^{31}-1 operations.

Examples3

  1. Example 1

    Input
    3
    5 3
    3 2
    2 6
    
    Expected output
    90
    
  2. Example 2

    Input
    1
    500 500
    
    Expected output
    0
    
  3. Example 3

    Input
    2
    1 500
    500 1
    
    Expected output
    500