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: Runtime Error

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

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

    # dp
    # g[i][j][n] == [a, b]: 座標(i, j)にいてi行でn個itemを拾った状態
    # a = sum of values
    # b = list of values in row of i
    g = [[[None, None, None, None] for _ in range(c)] for _ in range(r)]
    if value[0][0] > 0:
        g[0][0][1] = [value[0][0], [value[0][0]]]
    else:
        g[0][0][0] = [[0, []]]

    # 0列
    for i in range(1, r):
        if value[i][0] > 0:
            if g[i-1][0][1] == None:
                g[i][0][1] = g[i-1][0][0].copy()
            else:
                g[i][0][1] = g[i-1][0][1].copy()
            g[i][0][1][0] += value[i][0]
            g[i][0][1][1] = [value[i][0]]
        else:
            if g[i-1][0][1] == None:
                g[i][0][0] = g[i-1][0][0].copy()
            else:
                g[i][0][0] = g[i-1][0][1].copy()
            g[i][0][0][1] = []

    # 0行
    for j in range(1, c):
        for k in range(4):
            if g[0][j-1][k] == None:
                continue
            if value[0][j] > 0:
                if k == 3:
                    g[0][j][3] = g[0][j-1][3].copy()
                    g[0][j][3][0] += value[0][j]
                    g[0][j][3][1].append(value[0][j])
                    g[0][j][3][1].sort(reverse=True)
                    g[0][j][3][0] -= g[0][j][3][1].pop(3)
                else:
                    g[0][j][k+1] = g[0][j-1][k].copy()
                    g[0][j][k+1][0] += value[0][j]
                    g[0][j][k+1][1].append(value[0][j])
            else:
                g[0][j][k] = g[0][j-1][k].copy()
            break

    for i in range(1, r):
        for j in range(1, c):
            if value[i][j] > 0:
                # 下
                for k in range(4):
                    if g[i-1][j][k] == None:
                        continue
                    if g[i][j][1] == None or g[i][j][1][0] < g[i-1][j][k][0] + value[i][j]:
                        g[i][j][1] = g[i-1][j][k].copy()
                        g[i][j][1][0] += value[i][j]
                        g[i][j][1][1] = [value[i][j]].copy()

                # 右
                for k in range(4):
                    if g[i][j-1][k] == None:
                        continue
                    if k == 3:
                        if g[i][j][3] == None or g[i][j][3][0] < g[i][j-1][3][0] + value[i][j] - min(g[i][j-1][3][1] + [value[i][j]]):
                            g[i][j][3] = g[i][j-1][3].copy()
                            g[i][j][3][0] += value[i][j]
                            g[i][j][3][1].append(value[i][j])
                            g[i][j][3][1].sort(reverse=True)
                            g[i][j][3][0] -= g[i][j][3][1].pop(3)
                    else:
                        if g[i][j][k+1] == None or g[i][j][k+1][0] < g[i][j-1][k][0] + value[i][j]:
                            g[i][j][k+1] = g[i][j-1][k].copy()
                            g[i][j][k+1][0] += value[i][j]
                            g[i][j][k+1][1].append(value[i][j])
                            
            else:
                # 下
                for k in range(4):
                    if g[i-1][j][k] == None:
                        continue
                    if g[i][j][0] == None or g[i][j][0][0] < g[i-1][j][k][0]:
                        g[i][j][0] = g[i-1][j][k].copy()
                        g[i][j][0][1] = []

                # 右
                for k in range(4):
                    if g[i][j-1][k] == None:
                        continue
                    if g[i][j][k] == None or g[i][j][k][0] < g[i][j-1][k][0]:
                            g[i][j][k] = g[i][j-1][k].copy()

    ans = 0
    for i in g[r-1][c-1]:
        if i != None and ans < i[0]:
            ans = i[0]
    print(ans)

main()

Submission status: Runtime Error

Solution code:
import sys


def read():
    return sys.stdin.readline().rstrip()


def main():
    r, c, k = map(int, read().split())
    items = [[0] * c for _ in range(r)]
    for _ in range(k):
        ri, ci, vi = map(int, read().split())
        items[ri - 1][ci - 1] = vi
    dp = [[[0] * 4 for _ in range(c)] for _ in range(r)]
    exist[0][0][0] = 1
    exist[0][0][1] = 1
    dp[0][0][1] = items[0][0]
    for i in range(r):
        for j in range(c):
            if i < r - 1:
                dp[i + 1][j][0] = max(max(dp[i][j]), dp[i + 1][j][0])
                dp[i + 1][j][1] = max(dp[i + 1][j][0] + items[i + 1][j], dp[i + 1][j][1])
            if j < c - 1:
                dp[i][j + 1][0] = max(dp[i][j][0], dp[i][j + 1][0])
                dp[i][j + 1][1] = max(dp[i][j][1], dp[i][j + 1][1])
                dp[i][j + 1][2] = max(dp[i][j][2], dp[i][j + 1][2])
                dp[i][j + 1][3] = max(dp[i][j][3], dp[i][j + 1][3])
                if items[i][j + 1] > 0:
                    dp[i][j + 1][1] = max(dp[i][j][0] + items[i][j + 1], dp[i][j + 1][1])
                    dp[i][j + 1][2] = max(dp[i][j][1] + items[i][j + 1], dp[i][j + 1][2])
                    dp[i][j + 1][3] = max(dp[i][j][2] + items[i][j + 1], dp[i][j + 1][3])
    print(max(dp[-1][-1]))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import math
from numba import njit,i8
import numpy as np

@njit((i8, i8, i8, i8[:]), cache=True)
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())

Submission status: Runtime Error

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

@njit((i8, i8, i8, i8[:]), cache=True)
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())

Submission status: Runtime Error

Solution code:
import numba
from numba import jit
import numpy as np
 
def main(r, c):
  dp = np.zeros((c+1, 4), np.int64)
  for i in range(r):
    new_dp = np.zeros((c+1, 4), np.int64)
    for j in range(4):
      new_dp[:,0] = np.maximum(new_dp[:,0], dp[:,j])
    dp = new_dp
    for k in range(c):
      for l in range(2, -1, -1):
        dp[k,l+1] = max(dp[k,l+1], dp[k,l]+item_map[i,k])
      for m in range(1,4):
        dp[k+1,m] = max(dp[k+1,m], dp[k,m])
  return max(dp[c-1,:])
 
R, C, K = map(int, input().split())
item_lis = list(list(map(int, input().split())) for i in range(K))
item_map = np.zeros((R, C), np.int64)
for i,j,k in item_lis:
  item_map[i-1,j-1] = k
 
print(main(R, C))
import numpy as np

def main(r, c):
  dp = np.zeros((c+1, 4), np.int64)
  for i in range(r):
    new_dp = np.zeros((c+1, 4), np.int64)
    for j in range(4):
      new_dp[:,0] = np.maximum(new_dp[:,0], dp[:,j])
    dp = new_dp
    for k in range(c):
      for l in range(2, -1, -1):
        dp[k,l+1] = max(dp[k,l+1], dp[k,l]+item_map[i,k])
      for m in range(1,4):
        dp[k+1,m] = max(dp[k+1,m], dp[k,m])
  return max(dp[c-1,:])
 
R, C, K = map(int, input().split())
item_lis = list(list(map(int, input().split())) for i in range(K))
item_map = np.zeros((R, C), np.int64)
for i,j,k in item_lis:
  item_map[i-1,j-1] = k
 
print(main(R, C))
提出情報
提出日時

Submission status: Runtime Error

Solution code:
R,C,k=map(int,input().split())
h=[]
w=[]
v=[]

for i in range(k):
  ss,tt,uu=map(int,input().split())
  h.append(ss-1)
  w.append(tt-1)
  v.append(uu)
  
dp=[[[0]*(C+1) for i in range(R+1)] for _ in range(k+1)]

for i in range(k):
  for s in range(R+1):
    cnt=0
    for t in range(C+1):
      if h[i]>s or w[i]>t:
        dp[i+1][s][t]=dp[i][s][t]

      else:
        s==h[i] and t==w[i]:
          

      if dp[i+1][s][t]!=dp[i+1][s][t-1]:
        cnt+=1

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

Submission status: Runtime Error

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n,m,k = inpl()
value = [[0 for _ in range(m)] for i in range(n)]
for _ in range(k):
    a,b,c = inpl()
    value[a-1][b-1] = c
dp = [0] * (4*(m+5)*(n+5))
def ind(i,j,k): 
    return 4*(n+1)*i + 4*j + k
for i in range(n):
    for j in range(m):
        for k in range(3)[::-1]:
            dp[ind(i,j,k+1)] = max(dp[ind(i,j,k+1)], dp[ind(i,j,k)] + value[i][j])
        for k in range(4):
            dp[ind(i+1,j,0)] = max(dp[ind(i+1,j,0)], dp[ind(i,j,k)])
            dp[ind(i,j+1,k)] = max(dp[ind(i,j+1,k)], dp[ind(i,j,k)])
# print(dp)
mx = 0
for k in range(4):
    mx = max(mx, dp[ind(n-1,m-1,k)])
print(mx)

Submission status: Runtime Error

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n,m,k = inpl()
value = [[0 for _ in range(m)] for i in range(n)]
for _ in range(k):
    a,b,c = inpl()
    value[a-1][b-1] = c
dp = [0] * (4*(m+5)*(n+5))
def ind(i,j,k): 
    return 4*(n+5)*i + 4*j + k
for i in range(n):
    for j in range(m):
        for k in range(3)[::-1]:
            dp[ind(i,j,k+1)] = max(dp[ind(i,j,k+1)], dp[ind(i,j,k)] + value[i][j])
        for k in range(4):
            dp[ind(i+1,j,0)] = max(dp[ind(i+1,j,0)], dp[ind(i,j,k)])
            dp[ind(i,j+1,k)] = max(dp[ind(i,j+1,k)], dp[ind(i,j,k)])
# print(dp)
mx = 0
for k in range(4):
    mx = max(mx, dp[ind(n-1,m-1,k)])
print(mx)

Submission status: Runtime Error

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n,m,k = inpl()
value = [[0 for _ in range(m)] for i in range(n)]
for _ in range(k):
    a,b,c = inpl()
    value[a-1][b-1] = c
dp = [0] * (4*(m+5)*(n+5))
def ind(i,j,k): 
    return 4*(n+5)*i + 5*j + k
for i in range(n):
    for j in range(m):
        for k in range(3)[::-1]:
            dp[ind(i,j,k+1)] = max(dp[ind(i,j,k+1)], dp[ind(i,j,k)] + value[i][j])
        for k in range(4):
            dp[ind(i+1,j,0)] = max(dp[ind(i+1,j,0)], dp[ind(i,j,k)])
            dp[ind(i,j+1,k)] = max(dp[ind(i,j+1,k)], dp[ind(i,j,k)])
# print(dp)
mx = 0
for k in range(4):
    mx = max(mx, dp[ind(n-1,m-1,k)])
print(mx)

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
from numba import njit, i8


@nb.njit(i8(i8, i8, i8[:, :], i8[:, :, :]), cache=True)
def move(R, C, V, point):

    point[0][0][1] = V[0][0]
    point[0][0][0] = 0

    for r in range(R):
        for c in range(C):

            # 列方向に動く
            if c > 0:
                point[r][c][3] = max(point[r][c - 1][2] + V[r][c], point[r][c - 1][3])
                point[r][c][2] = max(point[r][c - 1][1] + V[r][c], point[r][c - 1][2])
                point[r][c][1] = max(point[r][c - 1][0] + V[r][c], point[r][c - 1][1])
                point[r][c][0] = point[r][c - 1][0]

            # 行方向に動く
            m = max(point[r - 1][c])
            if r > 0:
                point[r][c][1] = max(m + V[r][c], point[r][c][1])
                point[r][c][0] = m

    return max(point[R - 1][C - 1])


def main():

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

    V = [[0 for _ in range(C)] for _ in range(R)]
    V = np.array(V)
    point = [[[0, 0, 0, 0] for _ in range(C)] for _ in range(R)]
    point = np.array(point)
    for _ in range(K):
        r, c, v = map(int, sys.stdin.readline().rstrip().split())
        V[r - 1][c - 1] = v

    a = move(R, C, V, point)

    # print(point)
    print(a)


main()

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
from numba import jit, i8


@nb.njit(i8(i8, i8, i8[:, :], i8[:, :, :]), cache=True)
def move(R, C, V, point):

    point[0][0][1] = V[0][0]
    point[0][0][0] = 0

    for r in range(R):
        for c in range(C):

            # 列方向に動く
            if c > 0:
                point[r][c][3] = max(point[r][c - 1][2] + V[r][c], point[r][c - 1][3])
                point[r][c][2] = max(point[r][c - 1][1] + V[r][c], point[r][c - 1][2])
                point[r][c][1] = max(point[r][c - 1][0] + V[r][c], point[r][c - 1][1])
                point[r][c][0] = point[r][c - 1][0]

            # 行方向に動く
            m = max(point[r - 1][c])
            if r > 0:
                point[r][c][1] = max(m + V[r][c], point[r][c][1])
                point[r][c][0] = m

    return max(point[R - 1][C - 1])


def main():

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

    V = [[0 for _ in range(C)] for _ in range(R)]
    V = np.array(V)
    point = [[[0, 0, 0, 0] for _ in range(C)] for _ in range(R)]
    point = np.array(point)
    for _ in range(K):
        r, c, v = map(int, sys.stdin.readline().rstrip().split())
        V[r - 1][c - 1] = v

    a = move(R, C, V, point)

    # print(point)
    print(a)


main()

Submission status: Runtime Error

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n,m,k = inpl()
value = [[0 for _ in range(m)] for i in range(n)]
for _ in range(k):
    a,b,c = inpl()
    value[a-1][b-1] = c
dp = [[[0 for _ in range(4)] for i in range(m)] for j in range(n)]
dp[0][0][1] = value[0][0]

for oy in range(n):
    for ox in range(m):
        ny = oy; nx = ox + 1
        if 0 <= ny < n and 0 <= nx < m:
            nva = value[ny][nx]
            for k in range(4):
                dp[ny][nx][k] = max(dp[ny][nx][k], dp[oy][ox][k])
                if k and nva:
                    dp[ny][nx][k] = max(dp[ny][nx][k], dp[oy][ox][k-1] + nva)
        ny = oy + 1; nx = ox
        if 0 <= ny < n and 0 <= nx < m:
            dp[ny][nx][0] = max(dp[oy][ox])
            if nva:
                dp[ny][nx][1] = dp[ny][nx][0] + nva
print(max(dp[-1][-1]))

Submission status: Runtime Error

Solution code:
import sys
import queue
import copy

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(tin())
mod=1000000007

#+++++

def rc_to_s(r,c):
	return str(r)+'_'+str(c)
	
def s_to_rc(s):
	r,c = map(int, s.split('_'))
	return r, c
	
class qqq:
	def __init__(self, n, base):
		self.l=[]
		self.sum=0
		self.num=0
		self.n_max=n
		self.base=base
	
	def update(self, v):
		if self.n_max==0:
			return 
			
		elif self.num==self.n_max and v > self.l[0]:
			self.l[0]=v
			self.l.sort()
			self.sum=sum(self.l)
			
		elif self.num < self.n_max:
			self.l.append(v)
			self.l.sort()
			self.sum += v
			self.num += 1
	
	def get_value(self):
		return self.sum+self.base
		
	def copy(self):
		ret=qqq(self.n_max, self.base)
		ret.l=self.l[:]
		ret.sum=self.sum
		ret.num=self.num
		return ret
			
			
def main():
	#a = int(input())
	r, c, k = tin()
	#s = input()
	dd={}
	for _ in range(k):
		ri, ci, vi = tin()
		dd[rc_to_s(ri-1,ci-1)]=vi
	
	cv=[0]*c
	pq=qqq(3, 0)
	for ci in range(c):
		ps = rc_to_s(0, ci)
		if ps in dd:
			pq.update(dd[ps])
		cv[ci]=pq.get_value()
	
	for ri in range(1, r):
		ncv = [0 for _ in range(c)]
		sts=[qqq(0,0),qqq(1,0),qqq(2,0),qqq(3,0)]
		
		for ci in range(c):
			sts[0].base = cv[ci]
			ps = rc_to_s(ri, ci)
			if ps in dd:
				tv = dd[ps]
				for iii in [3,2,1]:
					sts[iii].update(tv)
					if sts[iii].get_value() < sts[iii-1].get_value() + tv
					:
						sts[iii]=sts[iii-1].copy()
						sts[iii].n_max=iii
						sts[iii].update(tv)
				
			ncv[ci]= max([v.get_value() for v in sts])
		cv=ncv
		#pa(cv)
	return cv[-1]
		
	
	
	

		
	
	
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Runtime Error

Solution code:
R , C , K = map(int,input().split())
masu = [[0 for i in range(C)] for j in range(R)]
for i in range(K):
    r , c , v = map(int,input().split())
    masu[r-1][c-1] = v

dp0 = [[0 for i in range(C)] for j in range(R)]
dp1 = [[0 for i in range(C)] for j in range(R)]
dp2 = [[0 for i in range(C)] for j in range(R)] 
dp3 = [[0 for i in range(C)] for j in range(R)]

if masu[0][0] != 0:
    dp1[0][0] = masu[0][0]
for i in range(1,C):
    dp0[0][i] = max(dp0[0][i],dp0[0][i-1])
    dp1[0][i] = max(dp1[0][i],dp1[0][i-1])
    dp2[0][i] = max(dp2[0][i],dp2[0][i-1])
    dp3[0][i] = max(dp3[0][i],dp3[0][i-1])
    if masu[0][i] != 0:
        dp3[0][i] = max(dp3[0][i],dp2[0][i]+masu[0][i])
        dp2[0][i] = max(dp2[0][i],dp1[0][i]+masu[0][i])
        dp1[0][i] = max(dp1[0][i],dp0[0][i]+masu[0][i])


if R == 1:
    print(dp[-1][-1])
    exit()

for i in range(1,R):
    for j in range(C):
        dp0[i][j] = max(dp0[i][j],dp0[i-1][j],dp1[i-1][j],dp2[i-1][j],dp3[i-1][j])
        if j != 0:
            dp0[i][j] = max(dp0[i][j],dp0[i][j-1])
            dp1[i][j] = max(dp1[i][j],dp1[i][j-1])
            dp2[i][j] = max(dp2[i][j],dp2[i][j-1])
            dp3[i][j] = max(dp3[i][j],dp3[i][j-1])
        if masu[i][j] != 0:
            dp3[i][j] = max(dp3[i][j],dp2[i][j]+masu[i][j])
            dp2[i][j] = max(dp2[i][j],dp1[i][j]+masu[i][j])
            dp1[i][j] = max(dp1[i][j],dp0[i][j]+masu[i][j])
print(max(dp0[-1][-1],dp1[-1][-1],dp2[-1][-1],dp3[-1][-1]))

Submission status: Runtime Error

Solution code:
r,c,k = map(int,input().split())
dp = [[[0 for _ in range(4)] for _ in range(c+1)] for _ in range(r+1)]
g = [[0]*(c+1) for _ in range(r+1)]
for _ in range(k):
    a,b,v = map(int,input().split())
    g[a][b] = v

for i in range(r+1):
    for j in range(c+1):
        for m in range(4):
            here = dp[i][j][k]
            if i + 1 <= r:
                dp[i + 1][j][0] = max(dp[i + 1][j][0], here)
                dp[i + 1][j][1] = max(dp[i + 1][j][1], here + g[i + 1][j])
            if j + 1 <= c:
                dp[i][j + 1][k] = max(dp[i][j + 1][k], here)
                if k < 3:
                    dp[i][j + 1][k+1] = max(dp[i][j + 1][k+1], here + g[i][j + 1])
# ans = 0
            # tmp  =dp[i][j][m]
            # if i+1<=r:
            #     dp[i+1][j][0] = max(tmp,dp[i+1][j][0])
            #     dp[i+1][j][1] = max(dp[i+1][j][1],tmp + g[i+1][j])
            # if j+1<=c:
            #     dp[i][j+1][m] = max(dp[i][j+1][m],tmp)
            #     if m<3:
            #         dp[i][j+1][m+1] = max(dp[i][j+1][m+1],tmp + g[i][j+1]) 
print(max(dp[-1][-1]))

Submission status: Runtime Error

Solution code:
r,c,k = map(int,input().split())
dp = [[[0 for _ in range(4)] for _ in range(c+1)] for _ in range(r+1)]
g = [[0]*(c+1) for _ in range(r+1)]
for _ in range(k):
    a,b,v = map(int,input().split())
    g[a][b] = v

for i in range(r+1):
    for j in range(c+1):
        for m in range(4):
            here = dp[k][i][j]
            if i + 1 <= r:
                dp[0][i + 1][j] = max(dp[0][i + 1][j], here)
                dp[1][i + 1][j] = max(dp[1][i + 1][j], here + g[i + 1][j])
            if j + 1 <= c:
                dp[k][i][j + 1] = max(dp[k][i][j + 1], here)
                if k < 3:
                    dp[k + 1][i][j + 1] = max(dp[k + 1][i][j + 1], here + g[i][j + 1])
# ans = 0
            # tmp  =dp[i][j][m]
            # if i+1<=r:
            #     dp[i+1][j][0] = max(tmp,dp[i+1][j][0])
            #     dp[i+1][j][1] = max(dp[i+1][j][1],tmp + g[i+1][j])
            # if j+1<=c:
            #     dp[i][j+1][m] = max(dp[i][j+1][m],tmp)
            #     if m<3:
            #         dp[i][j+1][m+1] = max(dp[i][j+1][m+1],tmp + g[i][j+1]) 
print(max(dp[-1][-1]))

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
from numba import jit, void, i8
input = sys.stdin.readline

def main():
    R, C, K = map(int, input().split())

    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    cell = np.full((R+1, C+1), 0, dtype=np.int64)

    for i in range(K):
        x, y, c = map(int, input().split())
        cell[x-1][y-1] = c

    f(dp, cell, R, C)

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

@njit(void(i8[:,:,:],i8[:,:],i8,i8))
def f(dp, cell, R, C):
    dp[0][1][0] = dp[1][0][0] = 0
    for i in range(1, R + 1):
        for j in range(1, C + 1):
            for k in range(4):
                if k > 0:
                    dp[i][j][k] = max(dp[i][j][k], dp[i][j][k-1])
                dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k])
                if k > 0:
                    dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k-1] + cell[i-1][j-1])
                if k == 1:
                    dp[i][j][k] = max(dp[i][j][1], dp[i-1][j][3] + cell[i-1][j-1])

if __name__ == "__main__":
    main()

Submission status: Runtime Error

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 = defaultdict(int, 0)
    data = [NMI() for _ in range(K)]
    for r, c, v in data:
        grid[(r-1)*3001 + c-1] = v

    # dp = [[[0]*4 for _ in range(C+2)] for _ in range(R+2)]
    # (r, c, i) -> r * 10**8 + c * 10**4 + i
    def get_point(r, c, i):
        return r * 30010 + c * 10 + i

    dp = defaultdict(int, 0)
    for rc in range(R*(C+1) + C+1):
        r = rc // (C+1)
        c = rc % (C+1)
        if r > R or c > C: continue

        for i in range(4):
            now_point = get_point(r, c, i)
            r_point = get_point(r+1, c, 0)
            c_point_plus = get_point(r, c+1, i+1)
            c_point_non = get_point(r, c+1, i)

            now = dp[now_point]
            val = grid[r*3001 + c]

            if i == 3:
                # 取らずに下
                dp[r_point] = max(now, dp[r_point])
                continue

            # 取って下
            dp[r_point] = max(now + val, dp[r_point])
            # 取らずに下
            dp[r_point] = max(now, dp[r_point])
            # 取って横
            dp[c_point_plus] = max(now + val, dp[c_point_plus])
            # 取らずに横
            dp[c_point_non] = max(now, dp[c_point_non])

    dp_RC = [dp[get_point(R, C, 0) + i] for i in range(4)]
    print(max(dp_RC))


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
#ブログの模範解答（参考のため提出）
#https://marco-note.net/abc-175-work-log/

N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

ans = -float('inf')
for s in range(N):
    ### Step1
    S = []  # 累積和S. ただし, 初項は0ではなく1回目の移動後の得点とする.
    # 1回目の移動
    i = P[s] - 1
    S.append(C[i])
    # 2回目以降の移動. スタート地点に戻ってくるまで繰り返し.
    while i != s:
        i = P[i] - 1
        S.append(S[-1] + C[i])

    ### Step2: KとSの長に応じて場合分けして, 得点の最大値を求める.
    # 1周未満しか移動できない場合:
    if K <= len(S):
        score = max(S[:K])
    # 1周以上回ることができるが, ループを1周したときに得点が減る場合:
    elif S[-1] <= 0:
        score = max(S)
    # 1週以上回ることができ, かつループを1週するごとに得点が増える場合:
    else:
        # ループを (K // len(S) - 1)回 廻る場合:
        score1 = S[-1] * (K // len(S) - 1)
        score1 += max(S)
        # ループを (K // len(S))回 廻る場合:
        score2 = S[-1] * (K // len(S))
        r = K % len(S)
        if r != 0:
            score2 += max(0, max(S[:r]))
        # score1 と score2 の大きい方がこの場合の得点の最大値
        score = max(score1, score2)

    ans = max(ans, score)

print(ans)

Submission status: Runtime Error

Solution code:
r,c,k = map(int,input().split())
t = [[0 for i in range(c)] for i in range(r)]
for i in range(k):
    a,b,z = map(int,input().split())
    t[a-1][b-1] = z
dp = [[[0 for i in range(c)]for i in range(r)]for i in range(4)]
dp[0][0][0] = 0
dp[1][0][0] = t[0][0]
dp[2][0][0] = t[0][0]
dp[3][0][0] = t[0][0]
for i in range(r-1):
    dp[0][i+1][0] = dp[1][i][0]
    for j in range(1,4):
        dp[j][i+1][0] = dp[1][i][0]+t[i+1][0]
for i in range(c-1):
    dp[0][0][i+1] = 0
    for j in range(1,4):
        dp[j][0][i+1] = max(dp[1][0][i],t[0][i+1])
    for j in range(2,4):
        dp[j][0][i+1] = max(dp[2][0][i],dp[1][0][i]+t[0][i+1])
    dp[3][0][i+1] = max(dp[3][0][i],dp[2][0][i]+t[0][i+1])
for i in range(r-1):
    for j in range(c-1):
        for s in range(0,4):
            dp[s][i+1][j+1] =  max(dp[0][i+1][j],dp[3][i][j+1])
        for s in range(1,4):
            dp[s][i+1][j+1] = max(dp[0][i+1][j]+t[i+1][j+1],dp[1][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
        for s in range(2,4):
            dp[s][i+1][j+1] = max(dp[1][i+1][j]+t[i+1][j+1],dp[2][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
        dp[3][i+1][j+1] = max(dp[2][i+1][j]+t[i+1][j+1],dp[3][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
print(dp[3][r-1][c-1])

if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
if __name__=='__main__':


    r,c,k = map(int,input().split())
    t = [[0 for i in range(c)] for i in range(r)]
    for i in range(k):
        a,b,z = map(int,input().split())
        t[a-1][b-1] = z
    dp = [[[0 for i in range(c)]for i in range(r)]for i in range(4)]
    dp[0][0][0] = 0
    dp[1][0][0] = t[0][0]
    dp[2][0][0] = t[0][0]
    dp[3][0][0] = t[0][0]
    for i in range(r-1):
        dp[0][i+1][0] = dp[1][i][0]
        for j in range(1,4):
            dp[j][i+1][0] = dp[1][i][0]+t[i+1][0]
    for i in range(c-1):
        dp[0][0][i+1] = 0
        for j in range(1,4):
            dp[j][0][i+1] = max(dp[1][0][i],t[0][i+1])
        for j in range(2,4):
            dp[j][0][i+1] = max(dp[2][0][i],dp[1][0][i]+t[0][i+1])
        dp[3][0][i+1] = max(dp[3][0][i],dp[2][0][i]+t[0][i+1])
    for i in range(r-1):
        for j in range(c-1):
            for s in range(0,4):
                dp[s][i+1][j+1] =  max(dp[0][i+1][j],dp[3][i][j+1])
            for s in range(1,4):
                dp[s][i+1][j+1] = max(dp[0][i+1][j]+t[i+1][j+1],dp[1][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
            for s in range(2,4):
                dp[s][i+1][j+1] = max(dp[1][i+1][j]+t[i+1][j+1],dp[2][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
            dp[3][i+1][j+1] = max(dp[2][i+1][j]+t[i+1][j+1],dp[3][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
    print(dp[3][r-1][c-1])
main()