Problem:


Score : 500 points

Problem Statement

There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i.

Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square).

He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.

Find the maximum possible sum of the values of items he picks up.

Constraints

1 \leq R, C \leq 3000

1 \leq K \leq \min(2 \times 10^5, R \times C)

1 \leq r_i \leq R

1 \leq c_i \leq C

(r_i, c_i) \neq (r_j, c_j) (i \neq j)

1 \leq v_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R C K
r_1 c_1 v_1
r_2 c_2 v_2
:
r_K c_K v_K

Output

Print the maximum possible sum of the values of items Takahashi picks up.

Sample Input 1

2 2 3
1 1 3
2 1 4
1 2 5

Sample Output 1

8

He has two ways to get to the goal:

Visit (1, 1), (1, 2), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 5 = 8.

Visit (1, 1), (2, 1), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 4 = 7.

Thus, the maximum possible sum of the values of items he picks up is 8.

Sample Input 2

2 5 5
1 1 3
2 4 20
1 2 1
1 3 4
1 4 2

Sample Output 2

29

We have four items in the 1-st row. The optimal choices are as follows:

Visit (1, 1) (1, 2), (1, 3), (1, 4), (2, 4), and (2, 5), in this order, and pick up all items except the one on (1, 2). Then, the total value of the items he picks up will be 3 + 4 + 2 + 20 = 29.

Sample Input 3

4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10

Sample Output 3

142



Sample input:
2 2 3
1 1 3
2 1 4
1 2 5


Sample output:
8

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 II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def solve():
    dp0 = [0] * (w + 1)
    dp1 = [0] * (w + 1)
    dp2 = [0] * (w + 1)
    dp3 = [0] * (w + 1)
    for i in range(h):
        for j in range(w):
            v = vv[i * w + j]
            if v:
                dp3[j] = max(dp3[j], dp2[j] + v)
                dp2[j] = max(dp2[j], dp1[j] + v)
                dp1[j] = max(dp1[j], dp0[j] + v)
            dp3[j + 1] = max(dp3[j + 1], dp3[j])
            dp2[j + 1] = max(dp2[j + 1], dp2[j])
            dp1[j + 1] = max(dp1[j + 1], dp1[j])
            dp0[j] = max(dp1[j], dp2[j], dp3[j])
    print(dp0[-2])

h, w, k = MI()
vv = [0] * h * w
for _ in range(k):
    i, j, v = MI()
    i, j = i - 1, j - 1
    vv[i * w + j] = v
solve()

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int, sys.stdin.readline().rstrip().split())
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())


def main():
    R, C, K = MI()
    item = [[0] * (C + 1) for i in range(R + 1)]

    for i in range(K):
        r_, c_, v_, = MI()
        item[r_ - 1][c_ - 1] = v_

    dp = [[[0 for _ in range(C + 2)] for _ in range(R + 2)] for _ in range(4)]

    for i in range(R + 1):
        for j in range(C + 1):
            for k in range(4):
                a = dp[k][i][j]
                v = item[i][j]

                if k == 3:
                    dp[0][i + 1][j] = max(a, dp[0][i + 1][j])
                    continue
                dp[0][i + 1][j] = max(a, a + v, dp[0][i + 1][j])
                dp[k][i][j + 1] = max(a, dp[k][i][j + 1])
                dp[k + 1][i][j + 1] = max(a + v, dp[k + 1][i][j + 1])

    print(max(dp[0][R][C], dp[1][R][C], dp[2][R][C], dp[3][R][C]))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def main():
    R, C, K = NMI()
    item = [[0] * (C + 1) for i in range(R + 1)]

    for i in range(K):
        r_, c_, v_, = NMI()
        item[r_ - 1][c_ - 1] = v_

    dp = [[[0 for _ in range(C + 2)] for _ in range(R + 2)] for _ in range(4)]

    for i in range(R + 1):
        for j in range(C + 1):
            for k in range(4):
                a = dp[k][i][j]
                v = item[i][j]

                if k == 3:
                    dp[0][i + 1][j] = max(a, dp[0][i + 1][j])
                    continue
                dp[0][i + 1][j] = max(a, a + v, dp[0][i + 1][j])
                dp[k][i][j + 1] = max(a, dp[k][i][j + 1])
                dp[k + 1][i][j + 1] = max(a + v, dp[k + 1][i][j + 1])

    print(max(dp[0][R][C], dp[1][R][C], dp[2][R][C], dp[3][R][C]))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()
def make_grid_int(h, w, num): return [[int(num)] * w for _ in range(h)]
def main():
    R, C, K = NMI()
    grid = make_grid_int(R, C, 0)

    for i in range(K):
        r_, c_, v_, = NMI()
        grid[r_ - 1][c_ - 1] = v_

    dp = [[[0 for _ in range(C + 2)] for _ in range(R + 2)] for _ in range(4)]

    for i in range(R + 1):
        for j in range(C + 1):
            for k in range(4):
                a = dp[k][i][j]
                try:
                    v = grid[i][j]
                except:
                    v = 0

                if k == 3:
                    dp[0][i + 1][j] = max(a, dp[0][i + 1][j])
                    continue
                dp[0][i + 1][j] = max(a, a + v, dp[0][i + 1][j])
                dp[k][i][j + 1] = max(a, dp[k][i][j + 1])
                dp[k + 1][i][j + 1] = max(a + v, dp[k + 1][i][j + 1])

    print(max(dp[0][R][C], dp[1][R][C], dp[2][R][C], dp[3][R][C]))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def make_grid_int(h, w, num): return [[int(num)] * w for _ in range(h)]


def main():
    R, C, K = NMI()
    grid = make_grid_int(R, C, 0)
    for i in range(K):
        r, c, v = NMI()
        grid[r-1][c-1] = v

    dp = [[[0 for _ in range(C+2)] for _ in range(R+2)] for _ in range(4)]

    for r in range(R+1):
        for c in range(C+1):
            for i in range(4):
                now = dp[i][r][c]
                try:
                    val = grid[r][c]
                except:
                    val = 0

                if i == 3:
                    # 取らずに下
                    dp[0][r + 1][c] = max(now, dp[0][r + 1][c])
                    continue

                # 取って下
                dp[0][r+1][c] = max(now + val, dp[0][r+1][c])
                # 取らずに下
                dp[0][r+1][c] = max(now, dp[0][r+1][c])
                # 取って横
                dp[i+1][r][c+1] = max(now + val, dp[i+1][r][c+1])
                # 取らずに横
                dp[i][r][c+1] = max(now, dp[i][r][c+1])

    print(max(dp[0][R][C], dp[1][R][C], dp[2][R][C], dp[3][R][C]))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import numpy as np
import sys
input = sys.stdin.readline


def main():
    h, w, k = map(int, input().split())
    values = np.zeros((h, w), dtype=np.int64)
    items = np.array([list(map(int, input().split())) for _ in range(k)])
    ys, xs, vs = items[:, 0] - 1, items[:, 1] - 1, items[:, 2]
    values[ys, xs] = vs

    DP = np.zeros(w + 1, dtype=np.int64)
    for line in values:
        DP[1:] += line
        DP = np.maximum.accumulate(DP)
        for _ in range(2):
            DP[1:] = np.maximum(DP[:-1] + line, DP[1:])
            DP = np.maximum.accumulate(DP)
    print(DP[-1])


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
import heapq
from fractions  import gcd
#input=sys.stdin.readline
#import bisect

r,c,k=map(int,input().split())
v=[[0]*c for _ in range(r)]
for i in range(k):
    ri,ci,val=map(int,input().split())
    v[ri-1][ci-1]=val
d=[[0]*(c*r) for _ in range(4)]
d[1][0]=v[0][0]
for i in range(1,c):
    d[1][i]=max(d[1][i-1],d[0][i-1]+v[0][i])
    d[2][i]=max(d[2][i-1],d[1][i-1]+v[0][i])
    d[3][i]=max(d[3][i-1],d[2][i-1]+v[0][i])
for i in range(c,r*c):
    m=0
    for j in range(4):
        m=max(m,d[j][i-c])
    cx=i%c
    rx=i//c
    d[0][i]=max(0,m)
    d[1][i]=max(d[1][i-1],m+v[rx][cx],v[rx][cx]+d[0][i-1]) if cx!=0 else max(0,v[rx][cx]+m)
    d[2][i]=max(d[2][i-1],v[rx][cx]+d[1][i-1]) if cx!=0 else 0
    d[3][i]=max(d[3][i-1],v[rx][cx]+d[2][i-1]) if cx!=0 else 0
ans=0
for j in range(4):
  ans=max(ans,d[j][r*c-1])
print(ans)

Submission status: Accepted

Solution code:
import sys
def main():
    input = sys.stdin.readline
    R, C, k = map(int, input().split())
    s = [[0] * (C + 1) for i in range(R + 1)]
    dp = [[[0] * (C + 1) for i in range(R + 1)] for j in range(4)]
    for i in range(k):
        r, c, v = map(int, input().split())
        s[r][c] = v
    for i in range(R):
        for j in range(C):
            m = max(dp[0][i][j + 1], dp[1][i][j + 1], dp[2][i][j + 1], dp[3][i][j + 1])
            for k in range(4):
                if k == 0:
                    dp[k][i + 1][j + 1] = max(dp[k][i + 1][j], m)
                else:
                    dp[k][i + 1][j + 1] = max(dp[k][i + 1][j], dp[k - 1][i + 1][j] + s[i + 1][j + 1])
            dp[1][i + 1][j + 1] = max(dp[1][i + 1][j + 1], s[i + 1][j + 1] + m)
    print(max(dp[0][R][C], dp[1][R][C], dp[2][R][C], dp[3][R][C]))
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
R, C, K = map(int,input().split())
MAP = [[0 for i in range(C)] for j in range(R)]
DP = [[[0 for i in range(C+1)] for j in range(4)] for k in range(R+1)]
 
for _ in range(K):
    r, c, v = map(int,input().split())
    MAP[r-1][c-1] = v
 
for i in range(R):
    for j in range(4):
        for k in range(C):
            DP[i+1][j][k+1] = max(DP[i][3][k+1], DP[i+1][j][k])
            if j == 0:
                continue
            v = MAP[i][k]
            if v == 0:
                continue
            DP[i+1][j][k+1] = max(DP[i+1][j][k+1], max(DP[i][3][k+1], DP[i+1][j-1][k]) + v)

print(DP[R][3][C])

Submission status: Accepted

Solution code:
from numba import jit
import numpy as np

@jit
def main():
    R, C, K = map(int, input().split())
    scores = np.zeros((R,C), np.int64)
    for _ in range(K):
        r, c, v = map(int, input().split())
        scores[r-1][c-1] = v
    dp=np.zeros((R+1,C+1,4), np.int64)

    for i in range(1, R+1):
        for j in range(1, C+1):
            for k in range(4):
                dp[i][j][k] = max(dp[i][j-1][k],
                                dp[i-1][j][3])
            for k in range(3, 0, -1):
                dp[i][j][k] = max(dp[i][j][k],
                                  dp[i][j][k-1] + scores[i-1][j-1])

    
    return dp[R][C][3]

print(main())

Submission status: Accepted

Solution code:
import sys
input=lambda:sys.stdin.readline().rstrip()
r,c,k=map(int,input().split())
dp=[[(c+1)*[0]for _ in range(r+1)]for _ in range(4)]
p=[c*[0]for _ in range(r)]
for _ in range(k):
  rr,cc,u=map(int,input().split())
  rr-=1
  cc-=1
  p[rr][cc]=u
ans=0
for j in range(1,r+1):
  for k in range(1,c+1):
    dp[0][j][k]=max(dp[0][j-1][k],dp[0][j][k-1])
    t=max(dp[0][j-1][k],dp[1][j-1][k],dp[2][j-1][k],dp[3][j-1][k])
    for i in range(1,4):
      dp[i][j][k]=max(dp[i][j][k],t,dp[i][j][k-1])
      if p[j-1][k-1]:
        dp[i][j][k]=max(dp[i][j][k],dp[i-1][j][k-1]+p[j-1][k-1],t+p[j-1][k-1])
      ans=max(ans,dp[i][j][k])
print(ans)

Submission status: Accepted

Solution code:
import sys
import numpy as np
from collections import defaultdict
from numba import njit
def input(): return sys.stdin.readline().rstrip()

@njit('i8[:](i8[:],i8[:,:])')
def koushin(dp,item):
    dptmp1 = np.copy(dp)
    dptmp2 = np.copy(dp)
    dptmp3 = np.copy(dp)
    for i in range(len(item)):
        dptmp3[item[i][0]:] = np.fmax(dptmp3[item[i][0]:], dptmp2[item[i][0]]+item[i][1])
        dptmp2[item[i][0]:] = np.fmax(dptmp2[item[i][0]:], dptmp1[item[i][0]]+item[i][1])
        dptmp1[item[i][0]:] = np.fmax(dptmp1[item[i][0]:], dp[item[i][0]]+item[i][1])
    return dptmp3

def main():
    R, C, K = map(int, input().split())
    items = defaultdict(list)
    for _ in range(K):
        r, c, v = map(int, input().split())
        items[r-1].append([c-1, v])
    dp = np.zeros(C, dtype='int64')
    for RR in range(R):
        if items[RR]==[]:
          continue
        items[RR].sort(key=lambda x: x[0])
        dp=koushin(dp,np.array(items[RR],dtype='int64'))
    print(dp[-1])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import numpy as np
from collections import defaultdict
from numba import njit
def input(): return sys.stdin.readline().rstrip()

@njit
def koushin(dp,item):
    dptmp1 = np.copy(dp)
    dptmp2 = np.copy(dp)
    dptmp3 = np.copy(dp)
    for i in range(len(item)):
        dptmp3[item[i][0]:] = np.fmax(dptmp3[item[i][0]:], dptmp2[item[i][0]]+item[i][1])
        dptmp2[item[i][0]:] = np.fmax(dptmp2[item[i][0]:], dptmp1[item[i][0]]+item[i][1])
        dptmp1[item[i][0]:] = np.fmax(dptmp1[item[i][0]:], dp[item[i][0]]+item[i][1])
    return dptmp3

def main():
    R, C, K = map(int, input().split())
    items = defaultdict(list)
    for _ in range(K):
        r, c, v = map(int, input().split())
        items[r-1].append([c-1, v])
    dp = np.zeros(C, dtype=int)
    for RR in range(R):
        if items[RR]==[]:
          continue
        items[RR].sort(key=lambda x: x[0])
        dp=koushin(dp,np.array(items[RR],dtype=int))
    print(dp[-1])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque
import bisect
import copy
import heapq
import itertools
import math
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


class V:
    def __init__(self, f, v=None):
        self.f = f
        self.v = v
 
    def __str__(self):
        return str(self.v)
 
    def ud(self, n):
        if n is None:
            return

        if self.v is None:
            self.v = n
            return
        self.v = self.f(self.v, n) 


def main():
    R, C, K = read_values()
    V = [0] * (R * C)
    for _ in range(K):
        r, c, v = read_values()
        r -= 1
        c -= 1
        V[r * C + c] = v
    
    dp = [[0] * (R * C) for _ in range(4)]
    for i in range(R * C):
        r = i // C
        c = i % C
        if c + 1 < C:
            # not take
            for k in range(4):
                dp[k][i + 1]= max(dp[k][i + 1], dp[k][i])

            # take 
            for k in range(3):
                dp[k + 1][i + 1] = max(dp[k + 1][i + 1], dp[k][i] + V[i])

        # next r
        if r + 1 < R:
            for k in range(4):
                dp[0][i + C] = max(dp[0][i + C], dp[k][i] + (V[i] if k < 3 else 0))

    res = 0
    for k in range(4):
        res = max(res, dp[k][-1] + (V[-1] if k < 3 else 0))
    print(res)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

R,C,K=map(int,input().split())
J=[tuple(map(int,input().split())) for i in range(K)]

#DP0=[[0]*(C+2) for i in range(R+2)]
DP1=[[0]*(C+2) for i in range(R+2)]
DP2=[[0]*(C+2) for i in range(R+2)]
DP3=[[0]*(C+2) for i in range(R+2)]

MAP=[[0]*C for i in range(R)]

for x,y,v in J:
    MAP[x-1][y-1]=v

for i in range(R):
    for j in range(C):
        DP1[i][j]=max(DP1[i][j-1],DP1[i-1][j]+MAP[i][j],DP2[i-1][j]+MAP[i][j],DP3[i-1][j]+MAP[i][j])
        DP2[i][j]=max(DP2[i][j-1],DP1[i][j-1]+MAP[i][j])
        DP3[i][j]=max(DP3[i][j-1],DP2[i][j-1]+MAP[i][j])

ANS=0
for i in range(R):
    for j in range(C):
        ANS=max(ANS,DP1[i][j],DP2[i][j],DP3[i][j])
print(ANS)

Submission status: Accepted

Solution code:
R,C,K = map(int,input().split())
mat = {}
for _ in range(K):
  r,c,v = map(int,input().split())
  mat[(r,c)] = v

# dp[i][j][k] = i,jまでで、i列のものをk個取ったときのスコア
dp0 = [[0] * (C+1) for _ in range(R+1) ]
dp1 = [[0] * (C+1) for _ in range(R+1) ]
dp2 = [[0] * (C+1) for _ in range(R+1) ]
dp3 = [[0] * (C+1) for _ in range(R+1) ]

for i in range(1,R+1):
  for j in range(1,C+1):
    if (i,j) in mat:
      m = mat[(i,j)]
      # 左からの遷移
      dp1[i][j] = max(dp1[i][j-1], dp0[i][j-1]+m)
      dp2[i][j] = max(dp2[i][j-1], dp1[i][j-1]+m)
      dp3[i][j] = max(dp3[i][j-1], dp2[i][j-1]+m)
    else:
      dp1[i][j] = dp1[i][j-1]
      dp2[i][j] = dp2[i][j-1]
      dp3[i][j] = dp3[i][j-1]

    # 上からの遷移
    x = max(dp0[i-1][j], dp1[i-1][j], dp2[i-1][j], dp3[i-1][j])
    dp0[i][j] = max(dp0[i][j-1], x)
    if (i,j) in mat:
      m = mat[(i,j)]
      dp1[i][j] = max(dp1[i][j], x+m)
    else:
      dp1[i][j] = max(dp1[i][j], x)

print(max(dp0[R][C], dp1[R][C], dp2[R][C], dp3[R][C]))

Submission status: Accepted

Solution code:
import numpy as np
from numba import njit
def main():
    R, C, K = map(int, input().split())
    field = np.full((R+1,C+1), 0, dtype='int64')
    dpt = np.full((R+1,C+1,4), 0, dtype='int64')
    for i in range(K):
        r, c, v = map(int, input().split())
        field[r][c] = v
    dp(R, C, field, dpt)
    print(max(dpt[-1][-1]))

@njit('i4(i4,i4,i8[:,:],i8[:,:,:])', cache=True)
def dp(R, C, field, dpt):
    for r in range(1, R+1):
        for c in range(1, C+1):
            for taken in range(4):
                max_v = 0
                if taken == 0:
                    max_v = max(dpt[r-1][c])
                    max_v = max(dpt[r][c-1][0], max_v)
                elif taken == 1:
                    max_v = max(dpt[r][c-1][taken-1] + field[r][c],
                                dpt[r][c-1][taken],
                                max(dpt[r-1][c]) + field[r][c])
                else:
                    max_v = max(dpt[r][c-1][taken-1] + field[r][c],
                                dpt[r][c-1][taken])
                dpt[r][c][taken] = max_v
    return 1

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    from sys import stdin
    def input():
        return stdin.readline().strip()

    r, c, k = map(int, input().split())
    v = [[0] * c for _ in range(r)]
    for _ in range(k):
        i, j, k = map(int, input().split())
        v[i-1][j-1] = k

    # dp[j][n] = j列にいて、n個itemを拾った時のアイテムの価値の合計の最大値
    # 1行ずつdpを更新する
    # 0行目
    value = v[0][0]
    if value == 0:
        dp = [[0] * 4]
    else:
        dp = [[0, value, value, value]]
    for j in range(1, c):
        value = v[0][j]
        if value == 0:
            dp.append(dp[j-1])
            continue
        a = dp[j-1].copy()
        b = [0, a[0]+value, a[1]+value, a[2]+value]
        for k in range(1, 4):
            if a[k] < b[k]:
                a[k] = b[k]
        dp.append(a)

    # i行目
    for i in range(1, r):
        pre = dp[0][3]
        value = v[i][0]
        if value == 0:
            new_dp = [[pre] * 4]
        else:
            new_dp = [[pre, pre+value, pre+value, pre+value]]
        for j in range(1, c):
            value = v[i][j]
            if value == 0:
                a = new_dp[j-1].copy()
                b = [dp[j][3]] * 4
                for k in range(4):
                    if a[k] < b[k]:
                        a[k] = b[k]
                new_dp.append(a)
            else:
                a = new_dp[j-1].copy()
                pre = dp[j][3]
                b = [pre, pre+value, pre+value, pre+value]
                d = [a[0], a[0]+value, a[1]+value, a[2]+value]
                for k in range(4):
                    if a[k] < b[k]:
                        a[k] = b[k]
                    if a[k] < d[k]:
                        a[k] = d[k]
                new_dp.append(a)
        dp = new_dp

    print(dp[c-1][3])

main()

Submission status: Accepted

Solution code:
def main():
  import sys
  input=sys.stdin.readline
  h,w,k=map(int,input().split())
  H=range(h)
  W=range(w)
  dp=[[[0]*w for j in H] for i in range(4)]
  for _ in range(k):
    r,c,v=map(int,input().split())
    dp[0][r-1][c-1]=v
  if dp[0][0][0]!=0:
    dp[1][0][0]=dp[0][0][0]
    dp[0][0][0]=0
  for y in H:
    for x in W:
      v=dp[0][y][x]
      dp[0][y][x]=0
      for i in range(4):
        if 0<x:
          if dp[i][y][x]<dp[i][y][x-1]:
            dp[i][y][x]=dp[i][y][x-1]
          if 0<i and v!=0 and dp[i][y][x]<dp[i-1][y][x-1]+v:
            dp[i][y][x]=dp[i-1][y][x-1]+v
        if 0<y:
          if dp[0][y][x]<dp[i][y-1][x]:
            dp[0][y][x]=dp[i][y-1][x]
          if v!=0 and dp[1][y][x]<dp[i][y-1][x]+v:
            dp[1][y][x]=dp[i][y-1][x]+v
  print(max([dp[i][h-1][w-1] for i in range(4)]))
main()

Submission status: Accepted

Solution code:
import sys
from collections import deque
import bisect
import copy
import heapq
import itertools
import math
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


def main():
    R, C, K = read_values()
    V = [0] * (R * C)
    for _ in range(K):
        r, c, v = read_values()
        r -= 1
        c -= 1
        V[r * C + c] = v
    
    dp = [0 for _ in range(R * C * 4)]
    for i in range(R * C):
        r = i // C
        c = i % C
        if c + 1 < C:
            # not take
            for k in range(4):
                dp[4 * (i + 1) + k] = max(dp[4 * (i + 1) + k], dp[4 * i + k])

            # take 
            for k in range(3):
                dp[4 * (i + 1) + k + 1] = max(dp[4 * (i + 1) + k + 1], dp[4 * i + k] + V[i])

        # next r
        if r + 1 < R:
            for k in range(4):
                dp[4 * (i + C)] = max(dp[4 * (i + C)], dp[4 * i + k] + (V[i] if k < 3 else 0))

    res = 0
    for k in range(4):
        res = max(res, dp[4 * (R * C - 1) + k] + (V[-1] if k < 3 else 0))

    print(res)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

R, C, K = map(int, sys.stdin.readline().split())

grid = [[0 for _ in range(C+1)] for _ in range(R+1)]
for _ in range(K):
    r, c, v = map(int, sys.stdin.readline().split())
    grid[r][c] = v

# r行目、c列目にいるときに、その行でアイテムをi個取得している場合の最大価値
dp0 = [[0 for _ in range(C+1)] for _ in range(R+1)]
dp1 = [[0 for _ in range(C+1)] for _ in range(R+1)]
dp2 = [[0 for _ in range(C+1)] for _ in range(R+1)]
dp3 = [[0 for _ in range(C+1)] for _ in range(R+1)]
# print(dp)
for r in range(1, R+1):
    for c in range(1, C+1):
        # 取らない
        dp0[r][c] = max((dp0[r][c-1], dp0[r-1][c], dp1[r-1][c], dp2[r-1][c], dp3[r-1][c]))
        dp1[r][c] = max(dp1[r][c-1], dp1[r][c])
        dp2[r][c] = max(dp2[r][c-1], dp2[r][c])
        dp3[r][c] = max(dp3[r][c-1], dp3[r][c])

        # 取る
        dp1[r][c] = max(dp0[r-1][c] + grid[r][c], dp1[r][c])
        dp1[r][c] = max(dp1[r-1][c] + grid[r][c], dp1[r][c])
        dp1[r][c] = max(dp2[r-1][c] + grid[r][c], dp1[r][c])
        dp1[r][c] = max(dp3[r-1][c] + grid[r][c], dp1[r][c])

        dp1[r][c] = max(dp0[r][c-1] + grid[r][c], dp1[r][c])
        dp2[r][c] = max(dp1[r][c-1] + grid[r][c], dp2[r][c])
        dp3[r][c] = max(dp2[r][c-1] + grid[r][c], dp3[r][c])


# print(dp0)
# print(dp1)
# print(dp2)
# print(dp3)
print(max((dp0[R][C], dp1[R][C], dp2[R][C], dp3[R][C])))

Submission status: Accepted

Solution code:
def main():
  import sys
  input = sys.stdin.readline

  r,c,k = map(int,input().split())
  b = [[0 for _ in range(c)] for _ in range(r)]
  for i in range(k):
    y,x,v = map(int,input().split())
    y -= 1
    x -= 1
    b[y][x] = v

  # dp[j][l]:(i,j)に居て、i行目のアイテムをl個拾ったときの価値最大値。
  dp = [[0 for _ in range(4)] for _ in range(c+1)]
  for i in range(r):
    for j in range(c):
      # アイテムを拾う遷移。個数が多い方から計算する。
      for l in range(2,-1,-1):
        dp[j][l+1] = max(dp[j][l]+b[i][j],dp[j][l+1])
      # 移動する遷移。行を移動する際は、拾ったアイテム数はリセットされる。
      for l in range(4):
        dp[j+1][l] = max(dp[j][l],dp[j+1][l])
        dp[j][0] = max(dp[j][l],dp[j][0])
  ans = 0
  for i in range(4):
    ans = max(dp[c-1][i],ans)
  print(ans)

main()

Submission status: Accepted

Solution code:
R,C,K=map(int,input().split())
l=[[0] * C for i in range(R)]
for i in range(K):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  l[a][b]=c
dp=[[0] * C for i in range(R)]
for i in range(R):
  kdp=[0]*4
  for j in range(C):
    if i>0:
      kdp[0]=max(kdp[0],dp[i-1][j])
    for k in range(2,-1,-1):
      kdp[k+1]=max(kdp[k+1],kdp[k]+l[i][j])
      dp[i][j]=max(dp[i][j],kdp[k+1])
print(dp[R-1][C-1])

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    H, W, k = map(int, input().split())
    grid = [[0] * W for _ in range(H)]
    for _ in range(k):
        r, c, v = map(int, input().split())
        grid[r - 1][c - 1] = v

    # dp[i][h][w]:h行目のアイテムをi個取得した時の、座標(h,w)における価値の最大値
    dp = [[[0] * W for _ in range(H)] for _ in range(4)]
    dp[1][0][0] = grid[0][0]
    for h in range(H):
        for w in range(W):
            for i in range(4):
                # 下に移動する場合
                if h + 1 < H:
                    # アイテムを取らない
                    dp[0][h + 1][w] = max(dp[0][h + 1][w], dp[i][h][w])
                    # アイテムを取る
                    dp[1][h + 1][w] = max(dp[1][h + 1][w], dp[i][h][w] + grid[h + 1][w])
                # 右に移動する場合
                if w + 1 < W:
                    # アイテムを取らない
                    dp[i][h][w + 1] = max(dp[i][h][w + 1], dp[i][h][w])
                    # アイテムを取る（但し、4個以上所持してはいけない）
                    if i + 1 < 4:
                        dp[i + 1][h][w + 1] = max(dp[i + 1][h][w + 1], dp[i][h][w] + grid[h][w + 1])
    res = 0
    for i in range(4):
        res = max(res, dp[i][-1][-1])
    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
R,C,K=map(int,input().split())
l=[[0] * C for i in range(R)]
for i in range(K):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  l[a][b]=c
dp=[0]*C
for i in range(R):
  ndp=[0]*C
  kdp=[0]*4
  for j in range(0,C):
    kdp[0]=max(kdp[0],dp[j])
    for k in range(2,-1,-1):
      kdp[k+1]=max(kdp[k+1],kdp[k]+l[i][j])
    ndp[j]=max(kdp)
  dp=ndp
print(dp[C-1])

Submission status: Accepted

Solution code:
R,C,K=map(int,input().split())
l=[[0] * C for i in range(R)]
for i in range(K):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  l[a][b]=c
dp=[0]*C
for i in range(R):
  ndp=[0]*C
  kdp=[0]*4
  kdp[0]=dp[0]
  kdp[1]=l[i][0]+dp[0]
  ndp[0]=kdp[1]
  for j in range(1,C):
    kdp[0]=max(kdp[0],dp[j])
    for k in range(2,-1,-1):
      kdp[k+1]=max(kdp[k+1],kdp[k]+l[i][j])
    ndp[j]=max(kdp)
  dp=ndp
print(dp[C-1])

Submission status: Accepted

Solution code:
import sys
from itertools import islice


def resolve(in_):
    R, C, K = map(int, next(in_).split())
    _rcv = (map(int, line.split()) for line in islice(in_, K))

    R1 = R + 1
    C1 = C + 1
    R2 = R + 2
    C2 = C + 2
    limit_item = 3
    limit_item1 = limit_item + 1
    C2limit_item1 = C2 * limit_item1

    # grid = [[0] * C2 for _ in range(R2)]
    grid = [0] * (R2 * C2)
    for r, c, v in _rcv:
        # grid[r][c] = v
        grid[(r * C2) + c] = v

    
    # dp = [[[0] * limit_item1 for j in range(C2)] for i in range(R2)]
    dp = [0] * (R2 * C2 * limit_item1)
    # dp[1][1][1] = grid[1][1]
    dp[(1 * C2limit_item1) + (1 * limit_item1) + 1] = grid[(1 * C2) + 1]

    for i in range(1, R1):
        for j in range(1, C1):
            for k in range(limit_item1):
                # current = dp[i][j][k]
                current = dp[(i * C2limit_item1) + (j * limit_item1) + k]

                # left = grid[i][j + 1]
                left = grid[(i * C2) + (j + 1)]
                # dp[i][j + 1][k] = max(dp[i][j + 1][k], current)
                dp[(i * C2limit_item1) + ((j + 1) * limit_item1) + k] = max(dp[(i * C2limit_item1) + ((j + 1) * limit_item1) + k], current)
                if k < limit_item:
                    # dp[i][j + 1][k + 1] = max(dp[i][j + 1][k + 1], left + current)
                    dp[(i * C2limit_item1) + ((j + 1) * limit_item1) + (k + 1)] = max(dp[(i * C2limit_item1) + ((j + 1) * limit_item1) + (k + 1)], left + current)

                # top = grid[i + 1][j]
                top = grid[((i + 1) * C2) + j]
                # dp[i + 1][j][0] = max(dp[i + 1][j][0], current)
                dp[(i + 1) * C2limit_item1 + (j * limit_item1) + 0] = max(dp[(i + 1) * C2limit_item1 + (j * limit_item1) + 0], current)
                # dp[i + 1][j][1] = max(dp[i + 1][j][1], top + current)
                dp[(i + 1) * C2limit_item1 + (j * limit_item1) + 1] = max(dp[(i + 1) * C2limit_item1 + (j * limit_item1) + 1], top + current)
    # return max(dp[R][C])
    return max(dp[(R * C2limit_item1) + (C * limit_item1):((R + 1) * C2limit_item1) + ((C + 1) * limit_item1)])


def main():
    answer = resolve(sys.stdin.buffer)
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import math
from numba import jit
import numpy as np

@jit
def solve():
    
    r,c,k = map(int,input().split())

    value = np.zeros((r,c), dtype=np.int64)
    for i in range(k):
        r_t,c_t,v_t = map(int,input().split())
        value[r_t-1][c_t-1] = v_t

    dp = np.zeros((r,c,4), dtype=np.int64)
    dp[0][0][0] = 0

    for i in range(r):
        for j in range(c):
            for m in range(4):
                if i + 1 < r:
                    dp[i+1][j][0] = max(dp[i+1][j][0],dp[i][j][m])
                if j + 1 < c:
                    dp[i][j+1][m] = max(dp[i][j+1][m],dp[i][j][m])
                if value[i][j] != 0 and m < 3:
                    if i + 1 < r:
                        dp[i+1][j][0] = max(dp[i+1][j][0],dp[i][j][m]+value[i][j])
                    if j + 1 < c:
                        dp[i][j+1][m+1] = max(dp[i][j+1][m+1],dp[i][j][m]+value[i][j])

    for m in range(2,-1,-1):
        dp[r-1][c-1][m+1] = max(dp[r-1][c-1][m+1],dp[r-1][c-1][m]+value[r-1][c-1])
    return max(dp[r-1][c-1])

print(solve())