Go: package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

type Matrix struct {
	r int // num of row
	c int // num of column
}

type Range struct {
	start int // index, inclusive
	end   int // index, inclusive
}

func calcMultiplication(x, y Matrix) (Matrix, int) {
	if x.c != y.r {
		panic("cannnot calculate")
	}
	return Matrix{x.r, y.c}, x.r * y.c * x.c
}

func calcMinMatrixChainMultiplication(matrices []Matrix, r Range, memo map[Range]int) (Matrix, int) {
	if v, ok := memo[r]; ok {
		return Matrix{matrices[0].r, matrices[len(matrices)-1].c}, v
	}
	if len(matrices) == 0 {
		panic("must not be empty")
	} else if len(matrices) == 1 {
		return matrices[0], 0
	} else if len(matrices) == 2 {
		return calcMultiplication(matrices[0], matrices[1])
	}

	var minCount int = math.MaxInt32

	for i := 0; i < len(matrices)-1; i++ {
		formerMatrices := matrices[:i+1]
		latterMatrices := matrices[i+1:]
		matF, countF := calcMinMatrixChainMultiplication(formerMatrices, Range{0, i}, memo)
		matL, countL := calcMinMatrixChainMultiplication(latterMatrices, Range{i + 1, len(matrices) - 1}, memo)
		_, countFL := calcMultiplication(matF, matL)
		count := countF + countL + countFL
		if count < minCount {
			minCount = count
		}
	}
	return Matrix{matrices[0].r, matrices[len(matrices)-1].c}, minCount
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	n, _ := nextInt(sc)
	matrices := make([]Matrix, n)
	for i := 0; i < n; i++ {
		r, _ := nextInt(sc)
		c, _ := nextInt(sc)
		matrices[i] = Matrix{r, c}
	}
	memo := make(map[Range]int)
	_, resultCount := calcMinMatrixChainMultiplication(matrices, Range{0, len(matrices) - 1}, memo)
	fmt.Println(resultCount)
}

func nextInt(sc *bufio.Scanner) (int, error) {
	sc.Scan()
	return strconv.Atoi(sc.Text())
}

Python: #!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import re
import math
import collections
import itertools
import functools

DEBUG = True
DEBUG = False

def dbg(*args):
    if DEBUG:
        print("DBG: ", file=sys.stderr, end="")
        print(*args, file=sys.stderr)

Mat = collections.namedtuple("Mat", "r c")

def mat_mul(ms):
    return Mat(ms[0].r, ms[-1].c)

def cost(m1, m2):
    return m1.r * m1.c * m2.c

def solve(n, ms):
    if n == 1: return 0

    dp = {}
    for i in range(n):
        dp[(i,i)] = 0

    for l in range(2, n+1):
        for i in range(n-l+1):
            cost_min = math.inf
            #cost_min = float("inf")
            for j in range(l-1):
                dbg("l, i, j: %d %d %d", l, i, j)
                m_lhs = mat_mul(ms[i:i+j+1])
                m_rhs = mat_mul(ms[i+j+1:i+l])
                dbg("m_lhs, m_rhs: %r %r", m_lhs, m_rhs)
                cost_lhs = dp[(i,i+j)]
                cost_rhs = dp[(i+j+1,i+l-1)]
                dbg("cost_lhs, cost_rhs: %d %d", cost_lhs, cost_rhs)
                cost_mul = cost(m_lhs, m_rhs)
                dbg("cost_mul: %d", cost_mul)
                cost_now = cost_mul + cost_lhs + cost_rhs
                dbg("cost_now: %d", cost_now)
                if cost_min > cost_now:
                    cost_min = cost_now
            dp[(i,i+l-1)] = cost_min

    dbg(dp)
    return dp[(0,n-1)]

def main():
    n = int(input())

    ms = []
    for _ in range(n):
        r,c = map(int, input().split())
        ms.append(Mat(r,c))

    print(solve(n, ms))

if __name__ == "__main__": main()

Python: import sys, itertools

n = int(sys.stdin.readline())
if n==1:
    print(0)
    quit()

MM = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]

amin = 0
m = MM[0][:]
for i in range(n-1):
    amin += m[0]*m[1]*MM[i+1][1]
    m[1]=MM[i+1][1]


for t in itertools.permutations(range(n-1), n-2):

    mm=[m[:] for m in MM]
    o = list(t)
    ans=0
    for _ in range(n-2):
        i = o.pop(0)
        ans += mm[i][0]*mm[i+1][1]*mm[i][1]
        if ans>amin: break
        mm[i][1] = mm[i+1][1]
        mm.pop(i+1)
        
        for j in range(len(o)):
            if o[j]>i: o[j] -=1
    else:
        ans += mm[0][0]*mm[0][1]*mm[1][1]
        if amin>ans: amin=ans


print(amin)

Python: # ALDS_10_B - 連鎖行列積

import sys

N = int(input())

M = []
for n in range(N):
    r, c = map(int, sys.stdin.readline().strip().split())
    if n == 0:
        M.append(r)
    M.append(c)


# dp 初期化
dp = [[float('inf')] * N for _ in range(N)]
for n in range(N):
    dp[n][n] = 0

# dp 更新
for l in range(1, N):
    for i in range(N - l):
        j = i + l
        for k in range(i, j):
            # print(f'k: {k}, i: {i}, j: {j}')
            dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + M[i] * M[k + 1] * M[j + 1])

# for i in range(len(dp)):
#     print(dp[i])

print(dp[0][N - 1])

Python: N = int(input())
RC = [0] * N
for i in range(N):
  RC[i] = list(map(int, input().split()))
  
dp = [[float("inf")] * (N + 1) for _ in range(N + 1)]
for l in range(N + 1):
  for r in range(l, N + 1):
    if abs(l - r) <= 1:
      dp[l][r] = 0
    elif abs(l - r) == 2:
      dp[l][r] = RC[l][0] * RC[l][1] * RC[l + 1][1]
      
#print(dp)
#print("")
now = 3
while now <= N:
  for l in range(N + 1):
    #print(l, now)
    r = l + now
    if r <= N:
      for k in range(l + 1, r):
        dp[l][r] = min(dp[l][r], dp[l][k] + dp[k][r] + RC[l][0] * RC[k][0] *RC[r - 1][1])
  now += 1
        
print(dp[0][N])

Python: n =int(input())
R = [0]*(n+1)
C = [0]*(n+1)
for u in range(n):
    R[u+1], C[u+1] = map(int, input().split())

INF = 10**18    
dp = [[INF]*(n+1) for _ in range(n+1)]
for i in range(1,n+1):
    dp[i][i] = 0
for l in range(1,n):
    for i in range(1,n+1-l):
        dp[i][i+l] = min(dp[i][k]+ dp[k+1][i+l] + R[i]*C[k]*C[i+l] for k in range(i,i+l))

print(dp[1][n])

Python: # coding: utf-8

INF = 1 << 60
n = int(input().rstrip())
r = [0 for _ in range(n+10)]
c = [0 for _ in range(n+10)]
# i番目の行列からj番目の行列までの最小値
dp = [[INF for _ in range(n+10)] for _ in range(n+10)]
for i in range(n):
    line = input().rstrip().split()
    r[i] = int(line[0])
    c[i] = int(line[1])
    
for i in range(n):
    dp[i][i] = 0

# 行列の距離が近い方から計算しなくてはいけない！
for l in range(1,n):
    for i in range(n - l):
        j = i + l
        for k in range(i,j):
            dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] + r[i]*c[k]*c[j])
            
print(dp[0][n-1])

Python: n = int(input())
m = [[0] * (n + 1) for _ in range(n + 1)]
z = [0] * (n + 1)
for i in range(n):
    z[i], z[i + 1] = map(int, input().split())
j = 0
for l in range(2, n + 1):
    for i in range(1, n - l + 2):
        j = i + l - 1
        m[i][j] = float("inf")
        for k in range(i, j):
            m[i][j] = min(m[i][j], m[i][k] + m[k + 1][j] + z[i - 1] * z[k] * z[j])
print(m[1][n])

Python: def s():
 n=int(input())+1
 e=[input().split()for _  in[0]*~-n]
 p=[int(e[0][0])]+list(int(x[1])for x in e)
 m=[[0]*n for _ in[0]*n]
 for i in range(n):
  for r in range(n-i-1):
   c=r+i+1
   for j in range(r+1,c):
    x=m[r][j]+m[j][c]+p[r]*p[j]*p[c]
    if 1>m[r][c]or m[r][c]>x:m[r][c]=x
 print(m[r][c])
s()

Python: # [New] Matrix Chain Multiplication using Dynamic Programming Formula
# https://www.youtube.com/watch?v=_WncuhSJZyA

n = int(input())

P = []
a, b = [int(i) for i in input().split()]
P.append(a)
P.append(b)
for _ in range(n - 1):
    _, b = [int(i) for i in input().split()]
    P.append(b)

dp = [[None] * (n + 1) for _ in range(n + 1)]  # 1-indexed table

for i in range(1, n + 1):
    dp[i][i] = 0

for r in range(2, n + 1):
    for i in range(1, n - r + 2):
        j = i + r - 1
        dp[i][j] = float("inf")
        for k in range(i, j):
            dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + P[i - 1] * P[k] * P[j])

print(dp[1][-1])