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.Collections.Generic;
using System.Linq;
using System.Text;

namespace _20170410_AOJ
{
    class ALDS1_10B
    {
        static void Main(string[] args)
        {
            for (;;)
            {
                string line = Console.ReadLine();
                if (string.IsNullOrEmpty(line))
                {
                    break;
                }

                int n = int.Parse(line);
                int[] rc = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
                int[] p = new int[n + 1];
                long[,] matrix = new long[n + 1, n + 1];
                p[0] = rc[0];
                p[1] = rc[1];
                for (int i = 2; i <= n; i++)
                {
                    int c = int.Parse(Console.ReadLine().Split(' ')[1]);
                    p[i] = c;
                }

                long min = Min(1, n, p, matrix);

                Console.WriteLine(min);
            }
        }

        static long Min(int i, int j, int[] p, long[,] matrix)
        {
            long rv;
            if (i == j)
            {
                rv = 0;
            }
            else if (matrix[i, j] > 0)
            {
                rv = matrix[i, j];
            }
            else
            {
                long min = long.MaxValue;
                for (int k = i; k < j; k++)
                {
                    long pqr = p[i - 1] * p[k] * p[j];
                    min = Math.Min(min, Min(i, k, p, matrix) + Min(k + 1, j, p, matrix) + pqr);
                }

                rv = min;
                matrix[i, j] = min;
            }

            return rv;
        }
    }
}