Problem:


Score : 600 points

Problem Statement

We will create an artwork by painting black some squares in a white square grid with 10^9 rows and N columns.

The current plan is as follows: for the i-th column from the left, we will paint the H_i bottommost squares and will not paint the other squares in that column.

Before starting to work, you can choose at most K columns (possibly zero) and change the values of H_i for these columns to any integers of your choice between 0 and 10^9 (inclusive).

Different values can be chosen for different columns.

Then, you will create the modified artwork by repeating the following operation:

Choose one or more consecutive squares in one row and paint them black. (Squares already painted black can be painted again, but squares not to be painted according to the modified plan should not be painted.)

Find the minimum number of times you need to perform this operation.

Constraints

1 \leq N \leq 300

0 \leq K \leq N

0 \leq H_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
H_1 H_2 ... H_N

Output

Print the minimum number of operations required.

Sample Input 1

4 1
2 3 4 1

Sample Output 1

3

For example, by changing the value of H_3 to 2, you can create the modified artwork by the following three operations:

Paint black the 1-st through 4-th squares from the left in the 1-st row from the bottom.

Paint black the 1-st through 3-rd squares from the left in the 2-nd row from the bottom.

Paint black the 2-nd square from the left in the 3-rd row from the bottom.

Sample Input 2

6 2
8 6 9 1 2 1

Sample Output 2

7

Sample Input 3

10 0
1 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000

Sample Output 3

4999999996



Sample input:
4 1
2 3 4 1


Sample output:
3

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n,k = LI()
h = [0] + LI()

dp = [[inf]*(n-k+1) for _ in range(n+1)]
dp[0][0] = 0
for i in range(1,n+1):
    for j in range(1,n-k+1):
        for l in range(i):
            dp[i][j] = min(dp[i][j],dp[l][j-1] + max(0,h[i]-h[l]))

ans = inf
for i in range(n+1):
    ans = min(ans,dp[i][n-k])
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
INF = 10**15
def solve(n, k, h):
    dp = np.full((n+1, n+1), INF, dtype=int)
    dp[0, 0] = 0
    h = np.array([0] + h, dtype=int)
    for i, h_i in enumerate(h[1:], 1):
        t = np.maximum(h_i - h[:i], 0)
        dp[i,1:] = np.min(dp[:i,:-1]+t[:,None], axis=0)
    return np.min(dp[:, n-k])

n, k = map(int, input().split())
h = list(map(int, input().split()))
print(solve(n, k, h))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
INTMAX = 9223372036854775807
INTMIN = -9223372036854775808
DVSR = 1000000007
def POW(x, y): return pow(x, y, DVSR)
def INV(x, m=DVSR): return pow(x, m - 2, m)
def DIV(x, y, m=DVSR): return (x * INV(y, m)) % m
def LI(): return [int(x) for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()
def II(): return int(input())
def FLIST(n):
    res = [1]
    for i in range(1, n+1): res.append(res[i-1]*i%DVSR)
    return res


N,K=LI()
MP=[0] + LI()
LG = 10**15
DP=[[LG]*(N+1) for i in range(N-K+2)]

for i in range(1, N+1):
    DP[0][i] = 0
    DP[1][i] = MP[i]

for i in range(1, N-K):
    for j in range(1, N+1):
        for k in range(1, j):
            DP[i+1][j] = min(DP[i+1][j], DP[i][k] + max(0, MP[j] - MP[k]))

res = 10**15
for i in range(1, N+1):
    res = min(res, DP[N-K][i])
print(res)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
H = [0] + [int(i) for i in input().split()]

dp = [[float('inf')] * (N - K + 1) for _ in range(N + 1)]
dp[0][0] = 0

# 右端がi、サイズがj
for i in range(1, N + 1) :
  for j in range(N - K + 1) :
    dp[i][j] = min(dp[k][j-1] + max(0, H[i] - H[k]) for k in range(i))

print(min(dp[i][N-K] for i in range(N + 1)))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
def resolve():
    n,k=map(int,input().split())
    H=[0]+list(map(int,input().split()))

    # dp[i][j] : i番目の要素をj個目に採用したときのcostのmin
    dp=[[INF]*(n-k+1) for i in range(n+1)]
    dp[0][0]=0

    for i in range(1,n+1):
        for j in range(1,n-k+1):
            dp[i][j]=min(dp[k][j-1]+max(0,H[i]-H[k]) for k in range(i))


    print(min(dp[i][n-k] for i in range(n+1)))
resolve()

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = list(map(int, input().split())) + [0]

#dp[a][b][c]: aまで見てb個消していて消してない右端がcのときの最小値(ぜんぶ1-indexed)
dp = [[[10**12 for _ in range(n+1)] for _ in range(k+1)] for _ in range(n+1)]
dp[0][0][0] = 0

for a in range(n):
	for b in range(k+1):

		for c in range(a+1):
			#h[a]を消す場合
			if b < k:
				dp[a+1][b+1][c] = min(dp[a+1][b+1][c], dp[a][b][c])

			#h[a]を消さない場合
			dp[a+1][b][a+1] = min(dp[a+1][b][a+1], dp[a][b][c] + max(0, h[a] - h[c-1]))

print(min(dp[n][k]))

Submission status: Accepted

Solution code:
def solve():
    from sys import stdin
    f_i = stdin
    
    N, K = map(int, f_i.readline().split())
    H = tuple(map(int, f_i.readline().split()))
    
    if N == K:
        return 0
    
    dp1 = list(H)
    for i in range(1, N - K):
        dp2 = dp1[:i]
        for x, H_x in enumerate(H[i:], start=i):
            v = min(dp_j + max(0, H_x - H_j) for dp_j, H_j in zip(dp1[i-1:x], H[i-1:x]))
            dp2.append(v)
        dp1 = dp2
    return min(dp1[N-K-1:])

print(solve())

Submission status: Accepted

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

if k == n:
    print(0)
    exit()

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

dp[0] = [] + h

for x in range(1, n-k):
    for y in range(n):
        temp = float('inf')
        for i in range(y):
            temp = min(temp, dp[x-1][i] + max(0, h[y] - h[i]))
        dp[x][y] = temp

#for x in dp: print(x)

print(min(dp[n-k-1]))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
H = [0] + list(map(int, input().split()))
dp = [[10 ** 100] * (N-K+1) for _ in range(N+1)]
dp[0][0] = 0
for x in range(1, N+1):
    for y in range(1, min(x+1, N-K+1)):
        dp[x][y] = min([dp[i][y-1] + max(H[x] - H[i], 0) for i in range(x)])
print(min([dp[i][N-K] for i in range(N+1)]))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
H = [0] + [int(a) for a in input().split()]
X = [[1<<100] * (N-K+1) for _ in range(N+1)]
X[0][0] = 0
for i in range(1, N+1):
    for j in range(1, min(i+1, N-K+1)):
        X[i][j] = min([X[ii][j-1] + max(H[i] - H[ii], 0) for ii in range(i)])

print(min([x[-1] for x in X]))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
H = list(map(int, input().split()))

N += 1
H = [0] + H

DP = [[float('inf')] * N for _ in range(N)]
DP[0][0] = 0
for i in range(1, N):
  DP[i][1] = H[i]
  for j in range(2, i + 1): 
    for k in range(1, i):
      DP[i][j] = min(DP[i][j], DP[k][j - 1] + max(0, H[i] - H[k]))

ans = float('inf')
for i in range(N):
    ans = min(ans, DP[i][N - K - 1])

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
H = [0] + [int(a) for a in input().split()]
X = [[1<<100] * (N-K+1) for _ in range(N+1)]
X[0][0] = 0
for i in range(1, N+1):
    for j in range(1, min(i+1, N-K+1)):
        X[i][j] = min([X[ii][j-1] + max(H[i] - H[ii], 0) for ii in range(i)])

print(min([x[-1] for x in X]))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
h=list(map(int,input().split()))
h.insert(0,0)
dp=[[float("inf")]*(n-k+1) for _ in range(n+1)]
dp[0][0]=0
for i in range(1,n+1):
    for j in range(1,n-k+1):
        now=float("inf")
        for l in range(i):
            now=min(dp[l][j-1]+max(0,h[i]-h[l]),now)
        dp[i][j]=now

ans=float("inf")
for i in range(1,n+1):
    ans=min(ans,dp[i][n-k])

print(ans if n>k else 0)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
H = list(map(int, input().split()))

# 全部消せる
if N <= K:
    print(0)
    exit()


dp = [[float('inf')] * (N + 1) for i in range(N + 1)]
dp[0][0] = 0
# 最初に使うとする場合には、その高さ分使う必要がある
for i, h in enumerate(H, start=1):
    dp[i][1] = h


for i in range(1, N + 1):
    for j in range(2, N + 1):
        for x in range(1, i):
            dp[i][j] = min(dp[i][j], dp[x][j - 1] + max(0, H[i - 1] - H[x - 1]))


ans = float('inf')
for i in range(N + 1):
    ans = min(ans, dp[i][max(0,  N - K)])

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
H = list(map(int, input().split()))
H = [0] + H


dp = [[float('inf')] * (N + 1) for i in range(N + 1)]
dp[0][0] = 0

for i in range(1, N + 1):
    for j in range(1, N + 1):
        for x in range(i):
            dp[i][j] = min(dp[i][j], dp[x][j - 1] + max(0, H[i] - H[x]))


ans = float('inf')
for i in range(N + 1):
    ans = min(ans, dp[i][max(0,  N - K)])

print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-


N,K=map(int, input().split())
H=list(map(int, input().split()))
G=[0]
G.extend(H[:])

dp=[[0]*(N+1) for i in range(N-K+1)]


tempa=0
if K<N-1:
    for jtemp in range(N):
        j=jtemp+1
        dp[1][j]=G[j]#min(dp[1][j-1],G[j])
    for itemp in range(N-K-1):
        i=itemp+2
        for jtemp in range(N-(i-1)):
            j=jtemp+i
            temp=int(N*1e9)
            
            for ktemp in range(j-(i-1)):
                k=ktemp+i-1
                val=G[j]-G[k]
                if val<0:
                    val=0
                if temp>dp[i-1][k]+val:
                    temp=dp[i-1][k]+val
            dp[i][j]=temp
    tempa=dp[N-K][-1]
    for jtemp in range(N):
        j=jtemp+1
        if tempa>dp[N-K][j] and dp[N-K][j]!=0:
            tempa=dp[N-K][j]
elif N-K==1:
    tempa=min(H[:])
else:
    tempa=0
print(tempa)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = list(map(int, input().split()))
INF = 10**18

k = n - k

dp = [[INF]*(k+1) for i in range(n+1)]
dp[0][0] = 0

# i番目のブロックを必ず選ぶ
for i in range(n):
    # すでにj回選んでいる
    for j in range(k):
        if j == 0:
            dp[i+1][j+1] = min(dp[0][j] + h[i], dp[i+1][j+1])
            continue
        #最後に選んだブロックはlast_i番目
        for last_i in range(i):
            if last_i + 1 < j:
                continue
            dp[i+1][j+1] = min(dp[last_i+1][j] + max(h[i] - h[last_i], 0), dp[i+1][j+1])

ans = 10**18
for i in range(n+1):
    ans = min(dp[i][k], ans)

print(ans)

Submission status: Accepted

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N,K = MI()
    H=LI()
    
    dp = [[0]+[inf]*(N) for _ in range(N)] #dp[right][size]: 最も右の項right, いじってないやつの数size
    for i in range(N):
        dp[i][1] = H[i]
    dp[0][1]=H[0]
    for right in range(N):
        for size in range(2,N+1):

            for i in range(right):
                dp[right][size] = min(dp[right][size], dp[i][size-1]+max(0, H[right]-H[i]))
    ans = inf 
    for i in range(N):
        ans = min(ans,dp[i][N-K])
    # print(*dp,sep="\n")
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
H = [0] + list(map(int, input().split())) + [0]

# dp[i][j] = minimum operations upto col i (fixed), with j moves remaining
dp = [[float('inf') for i in range(K+1)] for j in range(N+2)]
dp[0] = [0 for i in range(K+1)]

def cost(i, j):
    return max(0, H[j] - H[i])

for i in range(1, N+2):
    for j in range(K+1):
        for d in range(j+1):
            if i-d-1 < 0: break
            dp[i][j] = min(dp[i][j], cost(i-d-1, i) + dp[i-d-1][j-d])
                
print(dp[-1][K])

Submission status: Accepted

Solution code:
N, K = list(map(int, input().split()))
H = list(map(int, input().split()))

N += 1
H = [0] + H

inf = 10 ** 15
DP = [[inf] * N for _ in range(N)]
DP[0][0] = 0
for i in range(1, N):
  DP[i][1] = H[i]
  for j in range(2, i + 1): 
    for k in range(1, i):
      DP[i][j] = min(DP[i][j], DP[k][j - 1] + max(0, H[i] - H[k]))

ans = inf
for i in range(N):
    ans = min(ans, DP[i][N - K - 1])

print(ans)

Submission status: Accepted

Solution code:
import sys,bisect
input = sys.stdin.readline

n,k = map(int,input().split())
h = list(map(int,input().split()))
hs = [0]+sorted(h)

if k==0:
    res = h[0]
    for i in range(1,n):
        res += max(0,h[i]-h[i-1])
    print(res)
    exit()

#dp[i][j][l]: Hiまででj回使い最後がl番目の小ささの時の最小値
dp = [[[10**12]*(n+1) for i in range(k+1)] for j in range(n)]

kk = bisect.bisect_left(hs,h[0])
dp[0][0][kk] = h[0]
dp[0][1][0] = 0

for i in range(1,n):
    kk = bisect.bisect_left(hs,h[i])
    #Hi used in this turn
    for j in range(k+1):
        tmp = 10**12
        for l in range(n):
            tmp = min(tmp,dp[i-1][j][l]+max(0,hs[kk]-hs[l]))
        dp[i][j][kk] = tmp

    #not used
    for j in range(1,k+1):
        for l in range(n):
            dp[i][j][l] = min(dp[i][j][l],dp[i-1][j-1][l])

res = 10**12
for j in range(k+1):
    for l in range(n):
        res = min(res,dp[-1][j][l])
print(res)

Submission status: Accepted

Solution code:
def f_laminate(INF=float('inf')):
    # 参考: https://atcoder.jp/contests/abc145/submissions/8491285
    N, K = map(int, input().split())
    H = [0] + list(map(int, input().split()))

    # editorial と同じ DP テーブル
    dp = [[INF] * (N - K + 1) for _ in range(N + 1)]
    dp[0][0] = 0
    for x in range(1, N + 1):
        for y in range(1, N - K + 1):
            for i in range(x):
                dp[x][y] = min(dp[x][y], dp[i][y - 1] + max(0, H[x] - H[i]))

    ans = INF
    for i in range(N + 1):
        ans = min(ans, dp[i][N - K])
    return ans

print(f_laminate())

Submission status: Accepted

Solution code:
import numpy as np

n, k = map(int, input().split())
hhh = list(map(int, input().split()))
hhh = np.array([0] + hhh, dtype=np.int64)
INF = 10 ** 18
dp = np.full((n + 1, k + 1), fill_value=INF, dtype=np.int64)
dp[0, 0] = 0
for i, h in enumerate(hhh[1:], start=1):
    ndp = np.full((n + 1, k + 1), fill_value=INF, dtype=np.int64)
    ndp[:n, 1:] = dp[:n, :-1]
    ndp[i] = (dp + np.maximum(0, h - hhh)[:, np.newaxis]).min(axis=0)
    dp = ndp

print(dp.min())

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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

DP=[[1<<60]*(K+1) for i in range(N+2)]

for k in range(K+1):
    DP[0][k]=0

for i in range(1,N+2):
    
    for k in range(K+1):
        for j in range(k+1):
            DP[i][k]=min(DP[i][k],DP[i-j-1][k-j]+max(0,H[i]-H[i-j-1]))
        
print(min(DP[-1]))

Submission status: Accepted

Solution code:
def main():
    N, K = map(int, input().split())
    H = [0] + list(map(int, input().split()))
    dp = [[float("inf")] * (N+1) for _ in range(N+1)]
    dp[0][0] = 0
    for i in range(1, N+1):
        for j in range(i):
            diff = max(H[i] - H[j], 0)
            for k in range(min(N-K, j+1)):
                dp[i][k+1] = min(dp[i][k+1], dp[j][k] + diff)
    ans = float("inf")
    for i in range(N+1):
        ans = min(ans, dp[i][N-K])
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    n,k=map(int,input().split())
    H=[0]+list(map(int,input().split()))

    dp=[[INF]*(n-k+1) for _ in range(n+1)]
    dp[0][0]=0

    for x in range(1,n+1):
        for y in range(1,n-k+1):
            dp[x][y]=min(dp[x0][y-1]+max(0,H[x]-H[x0]) for x0 in range(x))

    print(min(dp[x][n-k] for x in range(n+1)))
resolve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    n,k=map(int,input().split())
    H=[0]+list(map(int,input().split()))

    dp=[[INF]*(n-k+1) for _ in range(n+1)]
    dp[0][0]=0

    for x in range(1,n+1):
        for y in range(1,n-k+1):
            dp[x][y]=min(dp[x0][y-1]+max(0,H[x]-H[x0]) for x0 in range(x))

    print(min(*(dp[x][n-k] for x in range(n+1))))
resolve()

Submission status: Accepted

Solution code:
import numpy as np

n, k = map(int, input().split())
h = np.array(input().split(), dtype=np.int)

if k < n:
  dp = np.zeros((n - k, n), dtype=np.int)
  dp[0] = h
  for i in range(n - k - 1):
    for j in range(i + 1, n):
      dp[i+1, j] = np.min(dp[i][i:j] + np.maximum(h[j] - h[i:j], 0))
  print(dp[n-k-1, n-k-1:].min())
else:
  print(0)

Submission status: Accepted

Solution code:
N,K = map(int, input().split())
H = [int(h) for h in input().split()]

dp = [[10**13]*N for _ in range(N)]
dp[0][0] = H[0]
    
for i in range(1, N):
    for j in range(i+1):
        if j == 0:
            dp[i][j] = H[i]
            continue
        for k in range(i):
            dp[i][j] = min(dp[i][j], dp[k][j-1]+max(0, H[i]-H[k]))
            
if N == K:
    ans = 0
else:
    ans = 10**13
    for i in range(N):
        ans = min(ans, dp[i][N-K-1])
        
print(ans)

Submission status: Accepted

Solution code:
inpl = lambda: list(map(int,input().split()))
N, K = inpl()
H = [0] + inpl() + [0]
dp = [[0]*(K+1) for _ in range(N+2)]
for n in range(1,N+2):
    for k in range(K+1):
        if k >= n-1:
            dp[n][k] = H[n]
        else:
            dp[n][k] = min(dp[n-1-l][k-l] + max(0,H[n]-H[n-1-l]) for l in range(k+1))
print(dp[-1][-1])

Submission status: Accepted

Solution code:
N, K = [int(s) for s in input().split(' ')]
H = [int(s) for s in input().split(' ')]

# state: up to nth column, how many skipped, current height(dict)
# value: how many times it takes to cover
dp = [[] for _ in range(N)]

for n, h in enumerate(H):
  if n == 0:
    before = [{0: 0}] + [{} for _ in range(K)]
  else:
    before = dp[n-1]
  # skip (k -> k+1)
  dp[n] = [{}] + before[:-1]
  current = dp[n]
  # not skip (update h and count)
  for k in range(K+1):
    # before[k] = current[k+1]
    for h_before, count in before[k].items():
      candidate = current[k].get(h, float("inf"))
      if h_before >= h:
        current[k][h] = min(candidate, count)
      else:
        current[k][h] = min(candidate, count + h - h_before)
      #print(n, k, h, h_before, count, candidate, current[k][h])
  #print(current)

print(min([v for d in dp[-1] for v in d.values()]))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
MOD = 10**9 + 7
INF = 10**13

n, K = [int(item) for item in input().split()]
h = [0] + [int(item) for item in input().split()]

# dp[i][j][k] i:till ith, j:skipped j, k: previous index
dp = [[[INF] * (n + 1) for _ in range(n + 1)] for _ in range(n + 1)]
for i, item in enumerate(h):
    if i == 0:
        dp[0][0][0] = 0
        continue
    for j in range(n-1, -1, -1):
        for k in range(n-1, -1, -1):
            if dp[i-1][j][k] == INF:
                continue
            # skip
            dp[i][j+1][k] = min(dp[i][j+1][k], dp[i-1][j][k])
            # use
            dp[i][j][i] = min(dp[i][j][i], dp[i-1][j][k] + max(0, h[i] - h[k]))
            
ans = INF
for j in range(n+1):
    ans = min(ans, dp[n][K][j])

print(ans)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")

def main():
    inf = 10 ** 16
    n, k = map(int, input().split())
    hh = [0] + list(map(int, input().split()))
    dp = [[0] * (k + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        h = hh[i]
        for j in range(k + 1):
            v = inf
            for nd in range(k + 1):
                if i - 1 - nd < 0 or j - nd < 0: break
                v = min(v, dp[i - 1 - nd][j - nd] + max(0, h - hh[i - 1 - nd]))
            dp[i][j] = v
    print(min(dp[n-d][k-d] for d in range(min(n+1,k+1))))

main()

Submission status: Accepted

Solution code:
def solve(n, k, h_list):
    if k == n:
        return 0
    # dp table
    large = sum(h_list) + 1
    dp = [[large] * n for _ in range(n + 1)]
    dp[1][0] = h_list[0]
    # update
    for i in range(1, n):
        for s in range(2, n + 1):
            dp[s][i] = min([dp[s - 1][j] + max(0, h_list[i] - h_list[j]) for j in range(i)])
        dp[1][i] = h_list[i]
    # print(dp)
    return min(dp[n - k])


def main():
    n, k = map(int, input().split())
    h_list = list(map(int, input().split()))
    res = solve(n, k, h_list)
    print(res)


def test():
    assert solve(4, 1, [2, 3, 4, 1]) == 3
    assert solve(6, 2, [8, 6, 9, 1, 2, 1]) == 7
    assert solve(10, 0, [1, 1000000000, 1, 1000000000, 1, 1000000000, 1, 1000000000, 1, 1000000000]) == 4999999996


if __name__ == "__main__":
    # test()
    main()

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')
from copy import deepcopy

#solve
def solve():
    n, k = LI()
    h = [0] + LI()
    d = defaultdict(int)
    d[(0, 0)] = 0
    for i in range(1, n + 1):
        nd = defaultdict(lambda: inf)
        for key, value in d.items():
            a, b = key
            if nd[(i, b)] > value + (h[i] - h[a] if h[i] > h[a] else 0):
                nd[(i, b)] = value + (h[i] - h[a] if h[i] > h[a] else 0)
            if b + 1 > k:
                continue
            if nd[(a, b + 1)] > value:
                nd[(a, b + 1)] = value
        d = nd
    ans = inf
    for i in range(n + 1):
        for j in range(k + 1):
            ans = min(ans, d[(i, j)])
    print(ans)
    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
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n,k = LI()
    h = LI()
    h.insert(0,0)
    dp = [[float("inf")]*(n+1) for i in range(n+1)]
    dp[0][0] = 0
    for i in range(n):
        ni = i+1
        hi = h[ni]
        for s in range(n):
            ns = s+1
            for j in range(ni):
                hj = h[j]
                nd = dp[j][s]+max(0,hi-hj)
                if nd < dp[ni][ns]:
                    dp[ni][ns] = nd
    ans = min([dp[i][n-k] for i in range(n+1)])
    print(ans)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import sys


N,K = map(int,input().split())

if N == K:
    print (0)
    sys.exit()

H = list(map(int,input().split()))


dp = [[None] * (N-K+1) for i in range(N) ]

for i in range(N):

    nh = H[i]

    dp[i][1] = nh

    for j in range(i):
        for k in range(N-K):

            if dp[j][k] != None:

                if dp[i][k+1] == None:
                    
                    dp[i][k+1] = dp[j][k] + max(0, H[i]-H[j])

                else:

                    dp[i][k+1] = min(dp[i][k+1] , dp[j][k] + max(0, H[i]-H[j]))

ans = float("inf")
for i in range(N):

    if dp[i][-1] != None:
        ans = min(ans,dp[i][-1])

print (ans)

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[]]*num
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################

N,K = II()
H = III()

if N==K:
    print(0)
    exit()

dp = [[float('inf')]*(N-K+1) for _ in range(N)]

for x in range(N):
    for y in range(N-K+1):
        if x+1<y:
            continue
        elif y==0:
            dp[x][y] = float('inf')
        elif y==1:
            dp[x][y] = H[x]
        else:
            val = float('inf')
            for i in range(x):
                now = dp[i][y-1] + max(0,H[x]-H[i])
                if now<val:
                    val = now
            dp[x][y] = val

ans = float('inf')
for i in range(N):
    if dp[i][N-K]<ans:
        ans = dp[i][N-K]

print(ans)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline

def main():
    n,k=map(int,input().split())
    H=[0]+list(map(int,input().split()))
    DP=[[10**12]*(n-k+1) for _ in range(n+1)]
    DP[0][0]=0
    for x in range(1,n+1):
        for y in range(1,n-k+1):
            for i in range(x):
                DP[x][y]=min(DP[x][y],DP[i][y-1]+max(0,H[x]-H[i]))
    print(min(DP[i][-1] for i in range(n+1)))

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline 




n,k = [int(i) for i in readline().split()]
a = [0]+[int(i) for i in readline().split()]

n += 1

INF = 10**18

K = n-k-1

dp = [[INF]*n for _ in range((K+1))]
dp[0][0] = 0



for i in range(1,n):
    ndp = [c[:] for c in dp]
    
    for l in range(min(i,K)):
        for now in range(0,i):
            ndp[l+1][i] = min(ndp[l+1][i], ndp[l][now]+max(0,a[i]-a[now]))
    
    dp = ndp
    #print(dp)    

#print(dp[-1])
print(min(dp[-1]))

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
H = list(map(int,input().split()))
H = [0]+H
dp = [[10**12]*(N+1) for _ in range(N+1)]
dp[0][0] = 0
for x in range(N+1):
    for y in range(1,N+1):
        for z in range(x):
            dp[x][y] = min(dp[x][y],dp[z][y-1]+max(H[x]-H[z],0))

ans = 10**12
for x in range(N+1):
    ans = min(dp[x][N-K],ans)

print(ans)

Submission status: Accepted

Solution code:
import sys
N, K = map(int, input().split())
H = list(map(int, input().split()))
if N<=K:
    print(0)
    sys.exit()
dp = [[[float('inf')]*(K+2) for i in range(N+2)] for j in range(N+1)]
dp[0][0][0] = H[0]
dp[0][-1][1] = 0
for i in range(N-1):
    for j in range(i+1):
        for k in range(K+1):
            if H[j]>H[i+1]:
                dp[i+1][j][k+1] = min(dp[i][j][k], dp[i+1][j][k+1])
                dp[i+1][i+1][k] = min(dp[i][j][k], dp[i+1][i+1][k])
            else:
                dp[i+1][i+1][k] = min(dp[i+1][i+1][k], dp[i][j][k]+H[i+1]-H[j])
                dp[i+1][j][k+1] = min(dp[i][j][k], dp[i+1][j][k+1])
    for k in range(K):
        dp[i+1][-1][k+1] = min(dp[i][-1][k], dp[i+1][-1][k+1])
        dp[i+1][i+1][k] = min(dp[i+1][i+1][k], dp[i][-1][k]+H[i+1])

ans = float('inf')
for i in range(K+1):
    res = min(dp[N-1][j][i] for j in range(N))
    ans = min(ans, res)
print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict

n, k = map(int, input().split())
hhh = list(map(int, input().split()))
INF = 10 ** 18
dp = defaultdict(lambda: INF)
dp[0] = 0
mask1 = (1 << 10) - 1
mask2 = ((1 << 63) - 1) ^ mask1

for h in hhh:
    ndp = defaultdict(lambda: INF)
    h_key = h << 10
    for changed_prev_h, operate in dp.items():
        changed = changed_prev_h & mask1
        prev_h = changed_prev_h >> 10
        if h == prev_h:
            key = h_key + changed
            ndp[key] = min(ndp[key], operate)
        elif h > prev_h:
            key = h_key + changed
            ndp[key] = min(ndp[key], operate + h - prev_h)
            if changed < k:
                key = changed_prev_h + 1
                ndp[key] = min(ndp[key], operate)
        else:
            key = h_key + changed
            ndp[key] = min(ndp[key], operate)
            if changed < k:
                key = changed_prev_h + 1
                ndp[key] = min(ndp[key], operate)
    # print(h)
    # print(dict(dp))
    # print(dict(ndp))
    dp = ndp
print(min(dp.values()))

Submission status: Accepted

Solution code:
# dp[i][j] := i 列目まで見て、i 列目を使うとして、
#             j 列無視した場合の min

N, K = map(int, input().split())
H = [0] + list(map(int, input().split())) + [0]
N += 1
inf = 10**18
dp = [[inf]*(K+1) for _ in range(N+1)]
dp[0][0] = 0
for i, h in enumerate(H[1:], 1):
    for j in range(K+1):
        for k in range(K+1):  # k 列無視する
            if i-k-1 < 0 or j-k < 0:
                continue
            h_p = H[i-k-1]
            dp[i][j] = min(dp[i][j], dp[i-k-1][j-k] + max(0, h - h_p))

#for d in dp:
#    print(d)
print(min(dp[-1]))