class Matrix
  attr_reader :dimensions

  def initialize(dimensions)
    @dimensions = dimensions
  end

  def scalar_multiplication_count(other)
    # Requires that matrixes can be multiplied.
    @dimensions[0] * @dimensions[1] * other.dimensions[1]
  end
end

class MatrixesMultiplication
  def initialize(matrixes)
    # Requires that matrixes can be multiplied.
    @matrixes = matrixes
  end

  def product(start_index, end_index)
    Matrix.new([
      @matrixes[start_index].dimensions[0],
      @matrixes[end_index].dimensions[1]
    ])
  end

  def min_multiplication_count
    if @min_multiplication_count_table.nil?
      create_min_multiplication_count_table
    end
    @min_multiplication_count_table[0][@matrixes.length - 1]
  end

  private def create_min_multiplication_count_table
    @min_multiplication_count_table = (0...@matrixes.length).map do
      Array.new
    end

    (1..@matrixes.length).each do |multiply_element_count|
      part_count = @matrixes.length - multiply_element_count + 1
      (0...part_count).each do |shift_count|
        part_start_index = shift_count
        part_end_index = part_start_index + multiply_element_count - 1
        save_min_partial_multiplication_count(
          part_start_index,
          part_end_index
        )
      end
    end
  end

  private def save_min_partial_multiplication_count(start_index, end_index)
    @min_multiplication_count_table[start_index][end_index] =
      min_partial_multiplication_count(start_index, end_index)
  end

  # Requires to be called incremental arguments.
  private def min_partial_multiplication_count(start_index, end_index)
    # Abbreviation
    t = @min_multiplication_count_table

    if end_index - start_index == 0
      return 0
    end

    multiply_element_count = end_index - start_index + 1
    options = (1..(multiply_element_count - 1)).map do |left_part_element_count|
      left_part_min_count =
        t[start_index][start_index + left_part_element_count - 1]
      right_part_min_count =
        t[start_index + left_part_element_count][end_index]
      left_product =
        product(start_index, start_index + left_part_element_count - 1)
      right_product =
        product(start_index + left_part_element_count, end_index)

      left_part_min_count + right_part_min_count +
        left_product.scalar_multiplication_count(right_product)
    end

    options.min
  end
end

n = gets.chomp.to_i
matrixes = (1..n).map do
  dimensions = gets.chomp.split(' ').map(&:to_i)
  Matrix.new(dimensions)
end

min_count = MatrixesMultiplication.new(matrixes).min_multiplication_count
puts min_count

