All problems

Problem 295

Matrix Chain Multiplication

Hard · 30 pts · Array, Dynamic Programming, Interval DP

Problem

You need to multiply a chain of N matrices M1 × M2 × ... × MN, where matrix Mi has D[i - 1] rows and D[i] columns. Multiplying a p x q matrix by a q x r matrix costs p × q × r scalar multiplications. Matrix multiplication is associative, so you can choose where to put the brackets, and different choices cost very different amounts. Find the minimum total cost. Use an interval DP: cost[i][j] is the cheapest way to multiply Mi to Mj, found by trying every split point k and adding cost[i][k] + cost[k + 1][j] + D[i - 1] × D[k] × D[j].

Input

First line: integer K = N + 1. Second line: the K dimensions D[0..N].

Output

Print the minimum cost.

Constraints

2 <= K <= 200; 1 <= D[i] <= 100

Example input

4
10 30 5 60

Example output

4500

Explanation

The matrices are 10x30, 30x5 and 5x60. Multiplying the first two costs 10 × 30 × 5 = 1500 and gives a 10x5 matrix, and multiplying that by the third costs 10 × 5 × 60 = 3000. The total of 4500 is cheaper than bracketing the other way (27000).

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Rod Cutting Next: Egg Dropping