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 C# (judge verdict: Accepted)

using System;
using System.Linq;
using System.Collections.Generic;

public class ALDS1_10_B
{
    public static void Main(string[] args)
    {
        //var exStdIn = new System.IO.StreamReader( "input.txt" );
        //System.Console.SetIn( exStdIn );

        int d = int.Parse(Console.ReadLine());
        List<Tuple<int, int>> m = new List<Tuple<int, int>>();
        for (int i = 0; i < d; i++)
        {
            int[] line = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
            m.Add(new Tuple<int, int>(line[0], line[1]));
        }
        Solve(m);
    }

    private static void Solve(List<Tuple<int, int>> m)
    {
        List<List<int>> dp = new List<List<int>>();
        for (int i = 0; i < m.Count; i++)
        {
            dp.Add(new List<int>());
            for (int j = 0; j < m.Count; j++)
            {
                if (i == j)
                {
                    dp[i].Add(0);
                }
                else
                {
                    dp[i].Add(-1);
                }
            }
        }
        for (int count = 2; count <= m.Count; count++)
        {
            for (int i = 0; i < m.Count - count + 1; i++)
            {
                int j = i + count - 1;
                Cul(i, j, m, dp);
            }
        }
        Console.WriteLine(dp[0][m.Count-1].ToString());
    }

    private static void Cul(int i, int j, List<Tuple<int, int>> m, List<List<int>> dp)
    {
        for (int k = i; k < j; k++)
        {
            int val = dp[i][k] + dp[k+1][j] + m[i].Item1 * m[k].Item2 * m[j].Item2;
            if (dp[i][j] == -1 || val < dp[i][j])
            {
                dp[i][j] = val;
            }
        }
    }
}