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)



Sample input:
4
10 20 30 40


Sample output:
190

Submission status: Accepted

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

dp = [[0]*440 for i in range(440)]
s = [[0]*440 for i in range(440)]
for l in range(n):
    s[l][l+1] = a[l]
    for r in range(l+2,n+1):
        s[l][r] = s[l][r-1] + a[r-1]

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

print(dp[0][n])

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
sys.setrecursionlimit(100000000)
MOD = 10**9+7
INF = 10 ** 20
from functools  import lru_cache

MAXN = 405
a = [0] * MAXN
dp = [[-1] * MAXN for _ in range(MAXN)]
def dfs(l,r):
    if dp[l][r] != -1:
        return dp[l][r]
    if r - l == 1:
        dp[l][r] = 0
        return 0
    ans = INF
    for i in range(l + 1,r):
        ans = min(ans,dfs(l,i) + dfs(i,r)) 
    if l == 0:
        ans += a[r - 1]
    else:
        ans += a[r - 1] - a[l - 1]
    dp[l][r] = ans
    return ans

def main():
    n = int(input())
    b = list(map(int,input().split()))
    a[:n] = b

    for i in range(1,n):
        a[i] += a[i - 1]
    
    ans = dfs(0,n)
    print(ans)
if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import accumulate
 
n = int(input())
acc = [0] + list(accumulate(map(int, input().split())))
dp = [[0] * (n + 1) for _ in range(n)]
for w in range(2, n + 1):
    for l in range(n - w + 1):
        r = l + w
        dp[l][r] = min(dp[l][m] + dp[m][r] for m in range(l + 1, r)) + acc[r] - acc[l]
print(dp[0][n])

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=[0]*(N+1)
for i in range(N):
  B[i+1]=B[i]+A[i]

dp=[[0]*(N+1) for i in range(N)]
#k:いくつのスライムを合体しているか
for k in range(2,N+1):
  #i:どこのスライムを起点に合体しているか
  for i in range(N-k+1):
    dp[i][k]=min(dp[i][j]+dp[i+j][k-j] for j in range(1,k))+B[i+k]-B[i]
print(dp[0][N])

Submission status: Accepted

Solution code:
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]
#print(prefixsum)
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):
        #starting index i and ending j
        #finally we need to print first row last column
        #which represent the cost of all the elements
        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])

Submission status: Accepted

Solution code:
#!usr/bin/env python3
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])

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
from itertools import accumulate
N = int(input())
a = list(map(int, input().split()))
cum = [0] + list(accumulate(a))
# dp[i][j] := merge i..j
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])

Submission status: Accepted

Solution code:
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:
        # print(l, r, "end", a[l] + a[r - 1])
        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

# print(dfs())
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])

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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)]
# dp[i][j] [i,j)の答え ans = dp[0][n]
for i in range(n):
    dp[i][i+1] = 0
for w in range(2,n+1): # w:区間の長さ
    for i in range(n):
        j = i + w # [i,j)で考える
        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])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
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 のコストを支払う。 
なお、合体の前後でスライムたちの位置関係は変わらない。
太郎君が支払うコストの総和の最小値を求めてください。
"""
#solve
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
        # print(dp, l, r)
        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])
        # print(l,r)
        dp[l][r] = tmp
        return tmp
    print(f(0, n))
    # print(dp)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
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 のコストを支払う。 
なお、合体の前後でスライムたちの位置関係は変わらない。
太郎君が支払うコストの総和の最小値を求めてください。
"""
#solve
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
        # print(dp, l, r)
        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])
        # print(l,r)
        dp[l][r] = tmp
        return tmp
    print(f(0, n))
    # print(dp)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
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):
        # print (dp[i, i:i + j], dp[i + 1:i + j + 1, i + 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])

Submission status: Accepted

Solution code:
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):
            # print (i, i + j, k + 1)
            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])

Submission status: Accepted

Solution code:
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):
        # print (dp[i, i:i + j], dp[i + 1:i + j + 1, i + 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])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
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])
# print(dp)

Submission status: Accepted

Solution code:
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():
    # LCS
    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():
    # http://zehnpaard.hatenablog.com/entry/2018/06/26/201512
    # トポロジカルソート
    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)
#    print(Order)
    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))
#    print(dp)
    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
#    print(dp)
    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
#    print(dp)
    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)
#    print(dp)
    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
#    print(dp)
    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
#        print(s,W,B)
        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()

"""

"""

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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()  # n
    a = [int(x) for x in input().split()]
    return slimes(a)


print(main())

Submission status: Accepted

Solution code:
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
        # 長さi+1, 開始位置jの合成コスト+構成要素の和
        if i == 0:
            o[span] = As[j]
            continue
        C = INF
#        print(i,j,o)
        for k in range(i):
            # 長さk+1とi+1-(k+1)=i-kに分割
#            print(i,j,k*N+j, (i-k-1)*N+j+k, o)
            C = min(C, o[k*N+j]+o[(i-k-1)*N+j+k+1])
#        o[span] = C + sum(As[j:j+i+1])
        o[span] = C + aa[j+i+1] - aa[j]

print(o[span]-ma)

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
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))  # type: int
    a = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, a)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    A = [int(a) for a in input().split()]
    INF = 10 ** 18
    dp = [[INF] * N for _ in range(N)]
    for i in range(N):
        dp[i][i] = 0
    acc = [0]
    for a in A:
        acc.append(acc[-1] + a)
    for w in range(2, N+1):
        for left in range(N):
            right = left + w - 1
            if right >= N:
                continue
            wsum = acc[right + 1] - acc[left]
            for mid in range(left, right):
                dp[left][right] = min(dp[left][right], dp[left][mid] + dp[mid+1][right] + wsum)
    print(dp[0][N-1])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
ruiseki = [0] * (n+1)
for i in range(n):
    ruiseki[i+1] = ruiseki[i] + a[i]

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

def solve(l, r):
    if dp[l][r] != -1:
        return dp[l][r]
    if r - l == 1:
        dp[l][r] = 0
        return dp[l][r]
    ans = 10**18
    for i in range(l+1, r):
        ans = min(ans, solve(l, i) + solve(i, r) + ruiseki[r] - ruiseki[l])
    dp[l][r] = ans
    return dp[l][r]

solve(0, n)
print(dp[0][n])

Submission status: Accepted

Solution code:
def f():
    import sys
    import numpy as np
    input=sys.stdin.readline
    n=int(input())
    a=np.array([0]+[int(j) for j in input().split()])
    np.cumsum(a,out=a)
    dp=np.zeros((n,n+1),np.int64)

    for i in range(1,n):
        l=np.arange(n-i)
        r=np.arange(i+1,n+1)
        m=(np.arange(1,i+1)+l[:,np.newaxis]).T
        dp[l,r]=np.amin(dp[l,m]+dp[m,r],0)+a[r]-a[l]
    print(dp[0][n])
f()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(160000)

N = int(input())
A = [int(a) for a in input().split()]

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

for i in range(N):
    flag[i][i] = True

S[0] = A[0]
for i in range(N):
    S[i+1] = S[i]+A[i]
    
def f(l, r):
    if flag[l][r]:
        return dp[l][r]
    flag[l][r] = True
    res = 10**18
    for m in range(l, r):
        res = min(res, f(l, m)+f(m+1, r))
    dp[l][r] = res+S[r+1]-S[l]
    return dp[l][r]

print(f(0, N-1))