Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Matrix-chain Multiplication

The goal of the matrix-chain multiplication problem is to find the most efficient way to multiply given $n$ matrices $M_1, M_2, M_3,...,M_n$.

Write a program which reads dimensions of $M_i$, and finds the minimum number of scalar multiplications to compute the maxrix-chain multiplication $M_1M_2...M_n$.

Input

In the first line, an integer $n$ is given. In the following $n$ lines, the dimension of matrix $M_i$ ($i = 1...n$) is given by two integers $r$ and $c$ which respectively represents the number of rows and columns of $M_i$.

Output

Print the minimum number of scalar multiplication in a line.

Constraints

$1 \leq n \leq 100$

$1 \leq r, c \leq 100$

Sample Input 1

6
30 35
35 15
15 5
5 10
10 20
20 25

Sample Output 1

15125

Solution in Scala (judge verdict: Accepted)

import scala.io.StdIn.{readLine, readInt};
object Main {
    def main(args: Array[String]): Unit = {
        val n = readInt;
        val p = new Array[Int](n + 1);
        (1 to n).foreach { i => 
            val input = readLine.split(" ").map(_.toInt);
            if (i == 1) p(0) = input(0);
            p(i) = input(1);
        }
        println(mcm(n, p));
    }
    def mcm(n: Int, p: Array[Int]): Int = {
        val dp = Array.ofDim[Int](n + 1, n + 1);
        (0 to n).foreach { y => (0 to n).foreach { x => if (y != x) dp(y)(x) = -1}};
        // y番目(包含)からx番目(包含)までの連鎖行列積を求める。
        def _go(y: Int, x: Int): Int = {
            if (dp(y)(x) != -1) {
                dp(y)(x);
            } else {
                // M1, M2, M3, M4 の中からコストが最小となるような区切り方を選択する。(y=1, x=4)
                //  [M1], [M2, M3, M4]  /  [M1, M2], [M3, M4]  /  [M1, M2, M3], [M4] 
                val min = (y until x).foldLeft(-1) { (minCost, sep) =>
                    // 今回の増分 = 左辺の行数 * 左辺の列数 * 右辺の列数
                    val incremental = p(y - 1) * p(sep) * p(x);
                    // 左辺の最小コスト * 右辺の最小コスト * 今回の増分
                    val cost = _go(y, sep) + _go(sep + 1, x) + incremental;
                    if (minCost > 0 && minCost < cost) minCost else cost;
                }
                dp(y)(x) = min;
                min;
            }
        }
        _go(1, n);
    }
}