Problem:
 Score : 100 points    Problem Statement There are N slimes lining up in a row.
Initially, the i -th slime from the left has a size of a_i .  Taro is trying to combine all the slimes into a larger slime.
He will perform the following operation repeatedly until there is only one slime:   Choose two adjacent slimes, and combine them into a new slime. The new slime has a size of x + y , where x and y are the sizes of the slimes before combining them. Here, a cost of x + y is incurred. The positional relationship of the slimes does not change while combining slimes.   Find the minimum possible total cost incurred.      Constraints  All values in input are integers.  2 \leq N \leq 400  1 \leq a_i \leq 10^9         Input Input is given from Standard Input in the following format:  N  a_1  a_2  \ldots  a_N       Output Print the minimum possible total cost incurred.        Sample Input 1 4
10 20 30 40      Sample Output 1 190  Taro should do as follows (slimes being combined are shown in bold):   ( 10 , 20 , 30, 40) → ( 30 , 30, 40)  ( 30 , 30 , 40) → ( 60 , 40)  ( 60 , 40 ) → ( 100 )        Sample Input 2 5
10 10 10 10 10      Sample Output 2 120  Taro should do, for example, as follows:   ( 10 , 10 , 10, 10, 10) → ( 20 , 10, 10, 10)  (20, 10 , 10 , 10) → (20, 20 , 10)  (20, 20 , 10 ) → (20, 30 )  ( 20 , 30 ) → ( 50 )        Sample Input 3 3
1000000000 1000000000 1000000000      Sample Output 3 5000000000  The answer may not fit into a 32-bit integer type.       Sample Input 4 6
7 6 8 6 1 1      Sample Output 4 68  Taro should do, for example, as follows:   (7, 6, 8, 6, 1 , 1 ) → (7, 6, 8, 6, 2 )  (7, 6, 8, 6 , 2 ) → (7, 6, 8, 8 )  ( 7 , 6 , 8, 8) → ( 13 , 8, 8)  (13, 8 , 8 ) → (13, 16 )  ( 13 , 16 ) → ( 29 )

Solution (Python):
n=int(input())
A=list(int(i) for i in input().split())
prefixsum=[0 for i in range(n+1)]
for i in range(1,n+1):
    prefixsum[i]=A[i-1]+prefixsum[i-1]

dp=[[0 for i in range(n)] for j in range(n)]
for i in range(n-1,-1,-1):
    for j in range(i,n):
        
        
        
        if i==j:
            dp[i][j]=0
        else:
            dp[i][j]=10**18
            for k in range(i,j):
                dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]+prefixsum[j+1]-prefixsum[i])
print(dp[0][-1])

Solution (Python):

import sys
import math
import string
import collections
import fractions
import random
from operator import itemgetter
import itertools
from collections import deque
import copy
import heapq
from bisect import bisect, bisect_left, bisect_right

MOD = 10 ** 9 + 7
INF = 10 ** 18
input = lambda: sys.stdin.readline().strip()

sys.setrecursionlimit(10 ** 8)

N = int(input())
a = list(map(int, input().split()))

dp = [[INF] * (N + 10) for _ in range(N + 10)]
dp2 = [[0] * (N + 10) for _ in range(N + 10)]

for l in range(N):
    dp[l][l] = a[l]

for i in range(N - 2, -1, -1):
    for j in range(i + 1, N):
        dp2[i][j] = min(dp[i][k] + dp2[k + 1][j] + dp2[i][k] + dp[k + 1][j] for k in range(i, j))
        for val in ([dp[i][k] + dp2[k + 1][j] + dp2[i][k] + dp[k + 1][j], k] for k in range(i, j)):
            if val[0] == dp2[i][j]:
                k = val[1]
        dp[i][j] = dp[i][k] + dp[k + 1][j]
print(dp2[0][N - 1])

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10000000)
    from collections import Counter, deque
    
    from itertools import combinations, permutations, accumulate
    
    from bisect import bisect_left,bisect_right
    import heapq
    from math import floor, ceil
    

    inf = 10**17
    

    N = int(input())
    a = list(map(int, input().split()))
    b = [0] + list(accumulate(a))
    dp = [[inf]*N for _ in range(N)]
    for i in range(N):
        dp[i][i] = 0
    for j in range(1, N):
        for l in range(0, N-j):
            r = l + j
            temp = b[r+1] - b[l]
            
            for k in range(l, r):
                dp[l][r] = min(dp[l][r], dp[l][k]+dp[k+1][r]+temp)
            
    print(dp[0][-1])

if __name__ == '__main__':
    main()

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
total_cost = 0

dp = [[0] * n for _ in range(n)]

for i in range(n-1, -1, -1):
    for j in range(i+1, n):
        min_cost = None

        for k in range(i, j):
            cost = dp[i][k] + dp[k+1][j]
            if min_cost is None or cost < min_cost:
                min_cost = cost

        dp[i][j] = min_cost + sum(a[i:j+1])

print(dp[0][-1])

Solution (Python):
from functools import lru_cache
N = int(input())
A = list(map(int, input().split()))

INF = 1.0e+100


dp = [[[None, INF] for _ in range(N+1)] for _ in range(N+1)]
for i in range(N):
    dp[i][i+1] = [A[i], 0]

for g in range(2, N+1):
    for l in range(N-g+1):
        r = l + g
        for i in range(l+1, r):
            lv, lc = dp[l][i]
            rv, rc = dp[i][r]
            nc = lv + rv + lc + rc
            if dp[l][r][1] > nc:
                dp[l][r][0] = lv + rv
                dp[l][r][1] = nc

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

Solution (Python):
n = int(input())
A = list(map(int, input().split()))

from itertools import accumulate
B = [0] + A
B = list(accumulate(B))

INF = 10**18
dp = [[INF]*(n+1) for i in range(n+1)]

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


for d in range(2, n+1):
    for i in range(n+1-d):
        j = i + d
        for k in range(i+1, j):
            dp[i][j] = min(dp[i][j], dp[i][k]+dp[k][j]+B[j]-B[i])

print(dp[0][n])

Solution (Python):
from itertools import accumulate
N = int(input())
a = list(map(int, input().split()))
cum = [0] + list(accumulate(a))

dp = [[0] * N for i in range(N)]
for l in range(1, N):
    for i in range(N-l):
        j = i + l
        dp[i][j] = cum[j+1] - cum[i] + min(dp[i][k] + dp[k+1][j] for k in range(i, j))
print(dp[0][N-1])

Solution (Python):
import itertools
n = int(input())
a = list(map(int, input().split()))

cs = list(itertools.accumulate(a)) + [0]

def score(l, r):
    return cs[r] - cs[l - 1]

dp = [[None] * (n + 1) for _ in range(n + 1)]
def dfs(l=0, r=n):
    if dp[l][r] is not None:
        return dp[l][r]

    if r - l == 2:
        
        value = a[l] + a[r - 1]
        dp[l][r] = value
        return value
    if r - l == 1:
        dp[l][r] = 0
        return 0

    scores = [dfs(l, c) + score(l, c - 1) + dfs(c, r) + score(c, r - 1) for c in range(l + 1, r)]
    value = min(scores)
    dp[l][r] = value
    return value


for l in reversed(range(n + 1)):
    for r in range(l + 1, n + 1):
        if r - l == 2:
            value = a[l] + a[r - 1]
            dp[l][r] = value
            continue
        if r - l == 1:
            dp[l][r] = 0
            continue

        scores = [dp[l][c] + score(l, c - 1) + dp[c][r] + score(c, r - 1) for c in range(l + 1, r)]
        value = min(scores)
        dp[l][r] = value
print(dp[0][n])

Solution (Python):
from itertools import accumulate
n = int(input())
a = list(map(int,input().split()))
acc = [0]+list(accumulate(a))
dp = [[10**18 for i in range(n)] for j in range(n)]
for w in range(n):
  for i in range(n-w):
    j = i+w
    if w == 0:
      dp[i][j] = 0
    elif w == 1:
      dp[i][j] = a[i]+a[j]
    else:
      for k in range(i,j):
        dp[i][j] = min(dp[i][j],dp[i][k]+dp[k+1][j]+acc[j+1]-acc[i])
print(dp[0][-1])

Solution (Python):
from itertools import accumulate

INF = float('inf')
N = int(input())
*A, = map(int, input().split())
cumsum = list(accumulate([0] + A))
dp = [[INF] * (N+1) for _ in range(N+1)]
for i in range(N): dp[i][i+1] = 0
for l in range(2, N+1):
    for i in range(N-l+1):
        j = i + l
        dp[i][j] = min([dp[i][k] + dp[k][j] for k in range(i+1, j)]) + (cumsum[j] - cumsum[i])
print(dp[0][N])

Solution (Python):
n = int(input())
a = list(map(int,input().split()))

cul = [0]
for x in a:
    cul.append(cul[-1]+x)

dp = [[10**13 for i in range(n+1)] for j in range(n+1)]

for i in range(n):
    dp[i][i+1] = 0
for w in range(2,n+1): 
    for i in range(n):
        j = i + w 
        if j > n:break
        for k in range(i,j):
            dp[i][j] = min(dp[i][j],dp[i][k]+dp[k][j]+cul[j]-cul[i])

print(dp[0][n])

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float("inf")

"""
URL: https://atcoder.jp/contests/dp/tasks/dp_n
N - Slimes / 
実行時間制限: 2 sec / メモリ制限: 1024 MB

配点 : 
100 点

問題文
N 匹のスライムが横一列に並んでいます。 
最初、左から i 番目のスライムの大きさは ai です。

太郎君は、すべてのスライムを合体させて 1 匹のスライムにしようとしています。 
スライムが 1 匹になるまで、太郎君は次の操作を繰り返し行います。

左右に隣り合う 2 匹のスライムを選び、それらを合体させて新しい 1 匹のスライムにする。 
合体前の 2 匹のスライムの大きさを x および y とすると、
    合体後のスライムの大きさは x+y となる。 
このとき、太郎君は x+y のコストを支払う。 
なお、合体の前後でスライムたちの位置関係は変わらない。
太郎君が支払うコストの総和の最小値を求めてください。
"""

def solve():
    n = II()
    a = LI()
    dp = [[0] * (n + 1) for i in range(n)]
    acc = [0] + list(itertools.accumulate(a))
    c = [[0] * (n + 1) for i in range(n)]
    def f(l, r):
        tmp = inf
        if c[l][r]: return dp[l][r]
        c[l][r] = 1
        
        if l + 1 == r: return 0
        
        
        for i in range(l + 1, r):
            tmp = min(tmp, f(l, i) + f(i, r) + acc[r] - acc[l])
        
        dp[l][r] = tmp
        return tmp
    print(f(0, n))
    
    return



if __name__ == '__main__':
    solve()

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = 1e18

"""
URL: https://atcoder.jp/contests/dp/tasks/dp_n
N - Slimes / 
実行時間制限: 2 sec / メモリ制限: 1024 MB

配点 : 
100 点

問題文
N 匹のスライムが横一列に並んでいます。 
最初、左から i 番目のスライムの大きさは ai です。

太郎君は、すべてのスライムを合体させて 1 匹のスライムにしようとしています。 
スライムが 1 匹になるまで、太郎君は次の操作を繰り返し行います。

左右に隣り合う 2 匹のスライムを選び、それらを合体させて新しい 1 匹のスライムにする。 
合体前の 2 匹のスライムの大きさを x および y とすると、
    合体後のスライムの大きさは x+y となる。 
このとき、太郎君は x+y のコストを支払う。 
なお、合体の前後でスライムたちの位置関係は変わらない。
太郎君が支払うコストの総和の最小値を求めてください。
"""

def solve():
    n = II()
    a = LI()
    dp = [[0] * (n + 1) for i in range(n)]
    acc = [0] + list(itertools.accumulate(a))
    c = [[0] * (n + 1) for i in range(n)]
    def f(l, r):
        tmp = inf
        if c[l][r]: return dp[l][r]
        c[l][r] = 1
        
        if l + 1 == r: return 0
        
        
        for i in range(l + 1, r):
            tmp = min(tmp, f(l, i) + f(i, r) + acc[r] - acc[l])
        
        dp[l][r] = tmp
        return tmp
    print(f(0, n))
    
    return



if __name__ == '__main__':
    solve()

Solution (Python):
import numpy as np

N = int(input())
A = [0] + list(map(int, input().split()))

A = np.array(A, dtype = np.int64)
A = np.cumsum(A)

dp = np.zeros((N, N), dtype = np.int64)

for j in range(1, N):
    for i in range(N - j):
        
        tmp = min(dp[i, i:i + j] + dp[i + 1:i + j + 1, i + j])
        dp[i, i + j] = tmp + A[i + j + 1] - A[i]

print (dp[0, N - 1])

Solution (Python):
N = int(input())
A = [0] + list(map(int, input().split()))

INF = 10 ** 18

dp = [[0] * (N) for _ in range(N)]

for i in range(N):
    A[i + 1] += A[i]

for j in range(1, N):
    for i in range(N - j):
        tmp = INF
        for k in range(i, i + j):
            
            tmp = min(tmp, dp[i][k] + dp[k + 1][i + j])
        dp[i][i + j] = tmp + A[i + j + 1] - A[i]

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

Solution (Python):
import numpy as np

N = int(input())
A = [0] + list(map(int, input().split()))

A = np.array(A, dtype = np.int64)
A = np.cumsum(A)

dp = np.zeros((N, N), dtype = np.int64)

for j in range(1, N):
    for i in range(N - j):
        
        tmp = min(dp[i, i:i + j] + dp[i + 1:i + j + 1, i + j])
        dp[i][i + j] = tmp + A[i + j + 1] - A[i]

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

Solution (Python):

import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

n = int(input())
A = list(map(int,input().split()))
dp = [[0]*(n+1) for i in range(n)]
for length in range(2,n+1):
  for i in range(n+1-length):
    j = i+length
    S = sum(A[i:j])
    tmp = inf
    for k in range(i+1,j):
      tmp = min(tmp,dp[i][k] + dp[k][j])
    dp[i][j] = tmp + S
print(dp[0][n])

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
dp = [[0] * (N + 1) for _ in range(N+ 1)]

accum = [0] * (N + 1)
for i in range(N):
    accum[i + 1] = accum[i] + A[i]

for m in range(1, N+1):
    for l in range(N):
        if m == 1:
            dp[l][l + m] = 0
        else:
            if l + m < N + 1:
                r = l + m
                dp[l][r] = min([dp[l][l+k] + dp[l+k][r] for k in range(1, m)]) + accum[r] - accum[l]

print(dp[0][N])

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
dp = [[-1]*N for _ in range(N)]
for i in range(N):
    dp[i][i] = 0


def main(l, r):
    if dp[l][r] != -1:
        return dp[l][r]
    ret = 10**15
    for i in range(l, r):
        ret = min(ret, main(l, i)+main(i+1, r))
    ret += sum(A[l:r+1])
    dp[l][r] = ret
    return ret


print(main(0, N-1))

Solution (Python):


N=int(input())
a=list(map(int,input().split()))

S=[0]*(N+1)
for i in range(N):
    S[i+1]=S[i]+a[i]



inf=10**15
dp=[[inf]*(N+1) for _ in range(N+1)]


for d in range(1,N+1):
    for i in range(N+1):
        j=i+d
        if j>N:
            break
        if d==1:
            dp[i][j]=0
        else:
            for k in range(i,j):
                dp[i][j]=min(dp[i][j] , dp[i][k]+dp[k][j]+S[j]-S[i])
            
print(dp[0][-1])

Solution (Python):
import sys
sys.setrecursionlimit(10**9)

n = int(input())
A = list(map(int, input().split()))

memo = [[float('inf')]*410 for _ in range(410)]
visit = [[False]*410 for _ in range(410)]

from itertools import accumulate
B = [0]+A
B = list(accumulate(B))

def dp(l, r):
  if l == r:
    return 0
  if visit[l][r]:
    return memo[l][r]
  visit[l][r] = True
  res = float('inf')
  for c in range(l, r):
    res = min(res, dp(l, c)+dp(c+1, r)+B[r+1]-B[l])
  memo[l][r] = res
  return res

print(dp(0, n-1))

Solution (Python):
def examA():
    N = I()
    H = LI()
    dp = [inf]*(N)
    dp[0] = 0
    for i in range(N-1):
        dp[i+1] = min(dp[i+1],dp[i]+abs(H[i+1]-H[i]))
        if i<N-2:
            dp[i + 2] = min(dp[i + 2], dp[i]+abs(H[i + 2] - H[i]))
    ans = dp[-1]
    print(ans)
    return

def examB():
    N, K = LI()
    H = LI()
    dp = [inf]*N
    dp[0] = 0
    for i in range(N):
        for k in range(1,K+1):
            if i+k>=N:
                break
            if dp[i+k]>dp[i]+abs(H[i+k]-H[i]):
                dp[i+k] = dp[i]+abs(H[i+k]-H[i])
    ans = dp[-1]
    print(ans)
    return

def examC():
    N = I()
    A = [0]*N; B = [0]*N; C = [0]*N
    for i in range(N):
        A[i],B[i],C[i] = LI()
    dp = [[0]*3 for _ in range(N+1)]
    for i in range(N):
        dp[i+1][0] = max(dp[i][1],dp[i][2]) + A[i]
        dp[i + 1][1] = max(dp[i][0], dp[i][2]) + B[i]
        dp[i + 1][2] = max(dp[i][1], dp[i][0]) + C[i]
    ans = max(dp[N])
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    
    S = SI(); N = len(S)
    T = SI(); M = len(T)
    dp = [[0] * (M + 1) for _ in range(N + 1)]
    for i in range(N):
        for j in range(M):
            if S[i] == T[j]:
                dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + 1)
            dp[i+1][j+1] = max(dp[i+1][j+1], dp[i+1][j], dp[i][j+1])

    i = N; j = M
    ans = []
    while i > 0 and j > 0:
        if dp[i][j] == dp[i-1][j]:
            i -= 1
        elif dp[i][j] == dp[i][j-1]:
            j -= 1
        else:
            ans.append(S[i-1])
            i -= 1
            j -= 1
    print("".join(ans[::-1]))
    return

def examG():
    
    
    def topological_sort(n,outs,ins):
        q = deque(v1 for v1 in range(n) if ins[v1] == 0)
        res = []
        while q:
            v1 = q.popleft()
            res.append(v1)
            for v2 in outs[v1]:
                ins[v2] -= 1
                if ins[v2] == 0:
                    q.append(v2)
        return res
    N, M = LI()
    V = [[]for _ in range(N)]
    start = [0]*N
    for _ in range(M):
        x,y = LI()
        x -= 1; y -= 1
        V[x].append(y)
        start[y] += 1
    Order = topological_sort(N, V, start)

    dp = [0]*N
    for i in Order:
        for v in V[i]:
            dp[v] = max(dp[v],dp[i]+1)
    ans = max(dp)
    print(ans)
    return

def examH():
    H, W = LI()
    A = [SI() for _ in range(H)]
    dp = [[0]*W for _ in range(H)]
    dp[0][0] = 1
    for i in range(H):
        for j in range(W):
            if A[i][j]=="
                continue
            dp[i][j] %=mod
            if i+1<H and dp[i+1][j]!="
                dp[i+1][j] +=dp[i][j]
            if j+1<W and dp[i][j+1]!="
                dp[i][j+1] +=dp[i][j]
    ans = dp[-1][-1]
    print(ans)
    return

def examI():
    N = I()
    P = LFI()
    dp = [[0]*(N+1) for _ in range(N+1)]
    dp[0][0] = 1
    for i in range(N):
        for j in range(i+1):
            dp[i+1][j+1] += dp[i][j]*P[i]
            dp[i+1][j] += dp[i][j]*(1-P[i])
    ans = 0
    for v in dp[N][(1+N//2):]:
        ans += v
    print(ans)
    return

def examJ():
    N = I()
    A = LI()
    dp = [[[0]*(N+1) for _ in range(N+1)]for _ in range(N+1)]
    S = Counter(A)
    print(S)
    dp[S[1]][S[2]][S[3]] = 0
    que = deque()
    que.append((S[1],S[2],S[3]))
    used = defaultdict(set)
    while(que):
        n1,n2,n3 = que.popleft()
        if used[(n1,n2,n3)]:
            continue
        used[(n1,n2,n3)] = True
        now = n1+n2+n3
        if n1>0:
            dp[n1-1][n2][n3] += dp[n1][n2][n3] + N/now * n1/now
            que.append((n1-1, n2, n3))
        if n2>0:
            dp[n1+1][n2-1][n3] += dp[n1][n2][n3] + N/now * n2/now
            que.append((n1+1,n2-1,n3))
        if n3>0:
            dp[n1][n2+1][n3-1] += dp[n1][n2][n3] + N/now * n3/now
            que.append((n1,n2+1,n3-1))

    ans = dp[0][0][0]
    print(ans)
    return

def examK():
    N, K = LI()
    A = LI()
    dp = [-1]*(K+1)
    for i in range(1,K+1):
        flag = False
        for a in A:
            if a>i:
                break
            if dp[i-a]==-1:
                flag = True
                break
        if flag:
            dp[i] = 1

    ans = dp[K]
    if ans==1:
        print("First")
    else:
        print("Second")
    return

def examM():
    N, K = LI()
    A = LI()
    dp = [[0]*(K+1) for _ in range(N+1)]
    dp[0][0] = 1
    for i in range(N):
        cum = [0]*(K+1)
        cum[0] = dp[i][0]
        for c in range(K):
            cum[c+1] = cum[c] + dp[i][c+1]
        for j in range(K+1):
            if j<=A[i]:
                dp[i+1][j] = cum[j]
            else:
                dp[i+1][j] = cum[j] - cum[j-A[i]-1]
            dp[i+1][j] %=mod

    ans = dp[N][K]%mod
    print(ans)
    return

def examN():
    N = I()
    A = LI()
    cumA = [0]*(N+1)
    for i in range(N):
        cumA[i+1] = cumA[i]+A[i]
    dp = [[inf]*(N) for _ in range(N)]
    for i in range(N):
        dp[0][i] = 0
    for i in range(N-1):
        for j in range(N-i-1):
            for k in range(i+1):
                cur = dp[i-k][j+k+1]+dp[k][j]+cumA[i+j+2]-cumA[j]
                dp[i+1][j] = min(dp[i+1][j],cur)

    ans = dp[N-1][0]
    print(ans)
    return

def examO():
    N = I()
    A = [LI() for _ in range(N)]
    loop = 2**N
    dp = [[0]*loop for _ in range(N+1)]
    dp[0][0] = 1
    for mask in range(loop):
        cur = 0
        for j in range(N):
            if mask&(1<<j)==(1<<j):
                cur +=1
        for i in range(N):
            if mask&(1<<i)==0 and A[i][cur]==1:
                dp[cur+1][mask|(1<<i)] += dp[cur][mask]
                dp[cur + 1][mask | (1 << i)] %=mod

    ans = dp[N][loop-1]
    print(ans)
    return

def examP():
    def dfs_dp(n,s,fords,visited):
        W = 1; B = 1
        visited[s] = True
        for v in fords[s]:
            if visited[v]:
                continue
            cur = dfs_dp(n, v, fords,visited)
            W *= sum(cur)
            B *= cur[0]
            W %= mod
            B %= mod

        return (W,B)
    N = I()
    V = [[]for _ in range(N)]
    for _ in range(N-1):
        x,y = LI()
        x -=1; y -=1
        V[x].append(y)
        V[y].append(x)
    visited = [False]*N
    ans = dfs_dp(N,0,V,visited)
    print(sum(ans)%mod)
    return

def examQ():
    N = I()
    H = LI()
    maxH = max(H)
    A = LI()
    dp = [0](maxH+1)
    cur = 0
    for i in range(N):
        dp[B[i]] = cur+dp[A[i]]
    return

def examR():
    def list_dot(A1,A2):
        res = [[0]*len(A2) for _ in range(len(A1))]
        for i in range(len(A1)):
            for j in range(len(A2)):
                cur = 0
                for k in range(len(A1[0])):
                    cur += A1[i][k]*A2[k][j]
                res[i][j] = cur%mod
        return res
    N, K = LI()
    A = [LI() for _ in range(N)]
    now = [[1]*N]
    while(K>0):
        if K%2==1:
            now = list_dot(now,A)
        K //=2
        A = list_dot(A,A)
    ans = 0
    for i in now:
        for k in i:
            ans += k
            ans %= mod
    print(ans)
    return

def examS():
    def ketadp(a):
        n = len(a)
        dp = defaultdict(int)
        dp[0, 0, 0] = 1
        for i, less, has3 in itertools.product(range(n), (0, 1), (0, 1)):
            max_d = 9 if less else int(a[i])
            for d in range(max_d + 1):
                less_ = less or d < max_d
                has3_ = has3 or d == 3
                dp[i + 1, less_, has3_] += dp[i, less, has3]

        ans = sum(dp[n, less, 1] for less in (0, 1))
        return ans
    K = SI()
    N = len(K)
    D = I()
    dp = [[0]*D for _ in range(N+1)]
    dp[0][0] = 1
    for i in range(N):
        if i==N-1:
            for j in range(D):
                for k in range(10):
                    dp[i + 1][(j + k) % D] += dp[i][j]
    ans = dp[N][0]
    print(dp)
    print(ans)
    return

import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LFI(): return list(map(float,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**6)

if __name__ == '__main__':
    examN()

"""

"""

Solution (Python):
N = int(input())
A = list(map(int, input().split()))

"""
cum = [[0]*(N) for i in range(N)]
for i in range(N):
  c = 0
  for j in range(i, N):
    c += A[j]
    cum[i][j] = c
"""
cum = [0]
for a in A:
  cum.append(cum[-1] + a)


dp = [[0]*N for i in range(N)]

for n in range(1, N+1):
  for i in range(N-n):
    j = i + n
    min_cost = 0
    for k in range(i, j):
      if min_cost == 0:
        min_cost = dp[i][k] + dp[k+1][j]
      else:
        min_cost = min(min_cost, dp[i][k]+dp[k+1][j])
    
    dp[i][j] = min_cost + (cum[j+1]-cum[i])

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

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

N = int(input())
A = [0]+list(map(int, input().split()))


Acum = A[::]
for i in range(N):
    Acum[i + 1] += Acum[i]


cost = [[-1] * (N + 1) for _ in range(N + 1)]
for i in range(N):
    cost[i][i + 1] = 0


def slime(i, j):
    if cost[i][j] != -1:
        return cost[i][j]

    res = 10 ** 18
    mass = Acum[j] - Acum[i]
    for x in range(i + 1, j):
        res = min(res, mass + slime(i, x) + slime(x, j))
    cost[i][j] = res
    return res


ans = slime(0, N)
print(ans)

Solution (Python):

def asum(l,r):
	global cumsum
	l+=1
	r+=1
	return cumsum[r-1]-cumsum[l-1]
def check(l,r):
	global dp
	if l==r:
		return 0
	if l == r-1:
		return arr[l]+arr[r]
	if dp[l][r] != None:
		return dp[l][r]
	else:
		ans = 10**18
		for i in range(l, r):
			st1 = asum(l,i)
			st2 = asum(i,r+1)
			ans = min(st1 + st2 + check(l,i)+ check(i+1, r), ans)
		
		dp[l][r] = ans
		return ans





ll = int(input())
arr = [int(i) for i in input().split()]
cumsum = [0]

for i in arr:
	cumsum.append(cumsum[-1]+i)
dp = [[None for i in range(ll+1)] for j in range(ll+1)]
print(check(0, ll-1))

Solution (Python):
import sys
sys.setrecursionlimit(10**8)

N = int(input())
*a, = map(int, input().split())

s = [0]*N
s[0] = a[0]
for i in range(1, N):
    s[i] += s[i-1]+a[i]
s = [0]+s

dp = [[0]*(N+1) for _ in range(N+1)]


def solve(l, r):
    if l == r:
        return 0
    if dp[l][r] > 0:
        return dp[l][r]

    n = float('inf')
    m = s[r+1]-s[l]
    for i in range(l, r):
        n = min([n, solve(l, i)+solve(i+1, r)+m])
    dp[l][r] = n
    return n


print(solve(0, N-1))

Solution (Python):
n = int(input())
a = list(map(int, input().split()))

dp = [[0] * n for _ in range(n) ]
sum_a = [[0] * n for _ in range(n) ]

for i in range(n):
    sum_a[i][i] = a[i]
    for j in range(i+1,n):
         sum_a[i][j] = sum_a[i][j-1] + a[j]

for i in range(1,n):
    for head in range(n-i):
        tail = head + i
        temp = 10**20
        for j in range(i):
            temp = min(temp, (dp[head][head+j] + dp[head+j+1][tail] + sum_a[head][tail]) )
        dp[head][tail] = temp

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

Solution (Python):
N = int(input())
A = list(map(int, input().split()))

cum = [[0]*(N) for i in range(N)]
for i in range(N):
  c = 0
  for j in range(i, N):
    c += A[j]
    cum[i][j] = c

dp = [[0]*N for i in range(N)]

for n in range(1, N+1):
  for i in range(N-n):
    j = i + n
    min_cost = 0
    for k in range(i, j):
      if min_cost == 0:
        min_cost = dp[i][k] + dp[k+1][j]
      else:
        min_cost = min(min_cost, dp[i][k]+dp[k+1][j])
    
    dp[i][j] = min_cost + cum[i][j]

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

Solution (Python):
N = int(input())
A = list(map(int, input().split()))

cum = [[0]*(N) for i in range(N)]
for i in range(N):
  c = 0
  for j in range(i, N):
    c += A[j]
    cum[i][j] = c

dp = [[0]*N for i in range(N)]

def get_min_cost(i, j):
  global dp
  if dp[i][j] > 0:
    return dp[i][j]
  else:
    min_cost = 0
    for k in range(i, j):
      if min_cost == 0:
        min_cost = get_min_cost(i, k) + get_min_cost(k+1, j) + cum[i][j]
      else:
        cost = get_min_cost(i, k) + get_min_cost(k+1, j) + cum[i][j]
        min_cost = min(min_cost, cost)
    
    dp[i][j] = min_cost
    return dp[i][j]

print(get_min_cost(0, N-1))

Solution (Python):
def slimes(a):
    n = len(a)
    d = [[0] * (n + 1) for _ in range(n + 1)]
    prefix = [0] * (n + 1)
    for i in range(1, n + 1):
        prefix[i] = prefix[i - 1] + a[i - 1]

    for l in range(2, n + 1):
        for x in range(n - l + 1):
            z = x + l
            d[x][z] = min(d[x][y] + d[y][z] for y in range(x + 1, z)) + (prefix[z] - prefix[x])

    return d[0][n]


def main():
    input()  
    a = [int(x) for x in input().split()]
    return slimes(a)


print(main())

Solution (Python):
N = int(input())
As = list(map(int, input().split()))
o = [0]*(N**2)
INF = 10**19
from itertools import accumulate
aa = [0] + list(accumulate(As))

for i in range(1, N+1):
    for j in range(N-i+1):
        span = (i-1)*N+j
        
        if i == 1:
            o[span] = As[j]
            continue
        C = INF
        for k in range(1, i):
            
            span1, span2 = (k-1)*N+j, (i-k-1)*N+j+k
            C = min(C, o[span1]+o[span2])
        o[span] = C + aa[(j+i-1)+1] - aa[(j-1)+1]
print(o[span]-aa[-1])

Solution (Python):
N = int(input())
As = list(map(int, input().split()))
ma = sum(As)
o = dict()
INF = 10**19
from itertools import accumulate
aa = [0] + list(accumulate(As))

for i in range(N):
    for j in range(N-i):
        span = i*N+j
        
        if i == 0:
            o[span] = As[j]
            continue
        C = INF

        for k in range(i):
            

            C = min(C, o[k*N+j]+o[(i-k-1)*N+j+k+1])

        o[span] = C + aa[j+i+1] - aa[j]

print(o[span]-ma)

Solution (Python):
def wczytaj_liste(): 
    wczytana_lista = input()
    lista_znakow = wczytana_lista.split()
    ostateczna_lista = []
    for element in lista_znakow:
        ostateczna_lista.append(int(element))
    return ostateczna_lista 

def potworny_Jan_Kanty():
    N = wczytaj_liste()[0]
    potwory = wczytaj_liste()
    wynik = [[None for i in range(N+1)]for j in range(N+1)]
    for dlugosc_przedzialu in range(1,len(potwory)+1):
        for poczatek in range(len(potwory)-dlugosc_przedzialu+1): 
            koniec = dlugosc_przedzialu + poczatek
            if dlugosc_przedzialu == 1:
                wynik[poczatek][koniec] = 0
            else:
                odp = 10**18
                for i in range(1, dlugosc_przedzialu):
                    kandydat = wynik[poczatek+i][koniec]+wynik[poczatek][poczatek+i]
                    if kandydat < odp: 
                        odp = kandydat
                wynik[poczatek][koniec] = odp+sum(potwory[poczatek:koniec])
    print(wynik[0][N])
    
potworny_Jan_Kanty()

Solution (Python):
n = int(input())
a = [int(x) for x in input().split()]

aa = [0]
for i in range(n):
    aa.append(a[i]+aa[i])

dp = [[10**12 for i in range(n+1)] for i in range(n+1)]

for i in range(1, n+1):
    for l in range(n):
        if i == 1:
            dp[l][l+i] = 0
        else:
            if l + i < n+1:
                dp[l][l+i] = min(dp[l][l+k] + dp[l+k][l+i] +
                                 aa[l+i] - aa[l] for k in range(1, i))

print(dp[0][n])

Solution (Python):

import sys
from itertools import accumulate
import functools
sys.setrecursionlimit(10**8)
INF = float("inf")


def solve(N: int, a: "List[int]"):

    dp = [[-1]*N for _ in range(N)]
    acc = [0]+list(accumulate(a))

    def rec(l, r):
        if dp[l][r] > 0:
            return dp[l][r]
        if l == r:
            return 0

        wa = acc[r+1]-acc[l]
        ans = INF
        for k in range(l, r):
            ans = min(rec(l, k) + rec(k+1, r), ans)
        dp[l][r] = ans + wa
        return dp[l][r]

    print(rec(0, N-1))
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    a = [int(next(tokens)) for _ in range(N)]  
    solve(N, a)


if __name__ == '__main__':
    main()