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:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal
from numba import jit

@jit
def run_dp(MAP, dp, R, C):
    for i in range(1, R+1):
        for j in range(1, C+1):
            for k in range(4):
                dp[i,j,0] = max(dp[i,j,0], dp[i-1,j,k])
                if MAP[i,j]:
                    dp[i,j,1] = max(dp[i,j,1], dp[i-1,j,k]+MAP[i,j])

                dp[i,j,k] = max(dp[i,j,k], dp[i,j-1,k])
                if MAP[i][j] and k < 3:
                    dp[i,j,k+1] = max(dp[i,j,k+1], dp[i,j-1,k] + MAP[i,j])
    return dp[R, C].max()

def run():
    R,C,K = map(int, sysread().split())
    MAP = np.zeros((R + 1, C + 1), dtype=np.int64)
    for i in range(K):
        r, c, v = map(int, sysread().split())
        MAP[r, c] = v

    dp = np.zeros((R+1, C+1, 4), dtype= np.int64)

    run_dp(MAP, dp, R, C)

    #print(dp)
    #for m in MAP:
    #   print(m)
    ans= run_dp(MAP, dp, Rs, Cs)

    print(ans)

if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
def main():
    r, c, k = map(int, input().split())
    d = [[0]*c for _ in [0]*r]
    for _ in range(k):
        t1, t2, t3 = map(int, input().split())
        d[t1-1][t2-1] = t3
    dp = [[0]*4 for _ in [0]*c]
    dp[0][1] = d[0][0]
    for x in range(r-1):
        d2 = d[x]
        dp2 = [[0]*4 for _ in [0]*c]
        for y in range(c-1):
            d3 = d2[y+1]
            for z in range(3):
                dp[y+1][z+1] = max(dp[y+1][z+1], dp[y][z]+d3)
            for z in range(4):
                dp[y+1][z] = max(dp[y+1][z], dp[y][z])
        d2 = d[x+1]
        for y in range(c):
            dp2[y][1] = max(dp2[y][1], max(dp[y])+d2[y])
            dp2[y][0] = max(dp2[y][0], max(dp[y]))
        dp = dp2
    for y in range(c-1):
        d3 = d2[y+1]
        for z in range(3):
            dp[y+1][z+1] = max(dp[y+1][z+1], dp[y][z]+d3)
        for z in range(4):
            dp[y+1][z] = max(dp[y+1][z], dp[y][z])
    print(max(dp[c-1]))


main()

Submission status: Runtime Error

Solution code:
def main():
    r, c, k = map(int, input().split())
    d = [[0]*c for _ in [0]*r]
    for _ in range(k):
        t1, t2, t3 = map(int, input().split())
        d[t1-1][t2-1] = t3
    dp = [[0]*4 for _ in [0]*c]
    dp[0][1] = d[0][0]
    for x in range(r-1):
        d2 = d[x]
        dp2 = [[0]*4 for _ in [0]*c]
        for y in range(c-1):
            d3 = d2[y+1]
            dp3 = dp[y+1]
            dp4 = dp[y]
            for z in range(3):
                dp3[z+1] = max(dp3[z+1], dp4[z]+d3)
            for z in range(4):
                dp3[z] = max(dp3[z], dp4[z])
        d2 = d[x+1]
        for y in range(c):
            dp3 = dp2[y]
            M = max(dp[y])
            dp3[1] = max(dp3[1], M+d2[y])
            dp3[0] = max(dp3[0], M)
        dp = dp2
    for y in range(c-1):
        d3 = d2[y+1]
        dp2 = dp[y+1]
        dp3 = dp[y]
        for z in range(3):
            dp2[z+1] = max(dp2[z+1], dp3[z]+d3)
        for z in range(4):
            dp2[z] = max(dp2[z], dp3[z])
    print(max(dp[c-1]))


main()

Submission status: Runtime Error

Solution code:
import heapq

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

cost = [[0 for i in range(C)] for j in range(R)] 

dp = [[0 for i in range(C)] for j in range(R+1)]

pick_up = [[[] for i in range(C)] for j in range(R)] 

for _ in range(K):
    r,c,v = map(int,input().split())
    r,c = r-1,c-1
    cost[r][c] = v

for h in range(R):
    for w in range(C):
        if w == 0:
            dp[h+1][w] = dp[h][w]+cost[h][w]
            if cost[h][w] != 0:
                heapq.heappush(pick_up[h][w],cost[h][w])
        else:
            if len(pick_up[h][w-1]) < 3:
                dp[h+1][w] = max(dp[h][w]+cost[h][w], dp[h+1][w-1]+cost[h][w])
                if cost[h][w] != 0:
                    if dp[h+1][w] == dp[h][w]+cost[h][w]:
                        heapq.heappush(pick_up[h][w],cost[h][w])
                    else:
                        tmp_array1 = copy.copy(pick_up[h][w-1])
                        heapq.heappush(tmp_array1,cost[h][w])
                        pick_up[h][w] = copy.copy(tmp_array1)
                else:
                    if dp[h+1][w] == dp[h][w]+cost[h][w]:
                        continue
                    else:
                        pick_up[h][w] = pick_up[h][w-1]
                    
            else:
                if cost[h][w] != 0:
                    tmp_array2 = copy.copy(pick_up[h][w-1])
                    minus = sum(tmp_array2)
                    heapq.heappush(tmp_array2,cost[h][w])
                    heapq.heappop(tmp_array2)
                    dp[h+1][w] = max(dp[h][w]+cost[h][w], dp[h+1][w-1]-minus+sum(tmp_array2))
                    if dp[h+1][w] == dp[h][w]+cost[h][w]:
                        heapq.heappush(pick_up[h][w],cost[h][w])
                    else:
                        pick_up[h][w] = copy.copy(tmp_array2)
                    
                else:
                    dp[h+1][w] = max(dp[h][w]+cost[h][w], dp[h+1][w-1]+cost[h][w])
                    if dp[h+1][w] == dp[h][w]:
                        continue
                    else:
                        pick_up[h][w] = copy.copy(pick_up[h][w-1])
    
            
print(dp[-1][-1])
#for i in cost:
    #print(*i)

#for i in pick_up:
    #print(*i)

Submission status: Runtime Error

Solution code:
from functools import lru_cache
import sys

sys.setrecursionlimit(1500)

n,m,k = [int(x) for x in input().split()]
v = []

@lru_cache(maxsize=8000000)
def solve(x, y, cnt):
  if x==n-1 and y == m-1:
    return 0
  
  ans = -1

  if y+1 < m:
    if cnt < 3 and v[x][y+1] != -1:
      ans = max(ans, solve(x, y + 1, cnt + 1) + v[x][y + 1])
    ans = max(ans, solve(x, y + 1, cnt))
  
  if x+1 < n:
    if v[x+1][y] != -1:
      ans = max(ans, solve(x + 1, y, 1) + v[x + 1][y])
    
    ans = max(ans, solve(x + 1, y, 0))
  
  return ans

for i in range(n):
  v.append([-1]*m)

for i in range(k):
  x,y,val = [int(x) for x in input().split()]
  x-=1
  y-=1
  v[x][y] = val

ans = solve(0,0,0)

if v[0][0] != -1:
  ans = max(ans, solve(0,0,1) + v[0][0])

print(ans)

Submission status: Runtime Error

Solution code:
from functools import lru_cache

n,m,k = [int(x) for x in input().split()]
v = []

@lru_cache(maxsize=8000000)
def solve(x, y, cnt):
  if x==n-1 and y == m-1:
    return 0
  
  ans = -1

  if y+1 < m:
    if cnt < 3 and v[x][y+1] != -1:
      ans = max(ans, solve(x, y + 1, cnt + 1) + v[x][y + 1])
    ans = max(ans, solve(x, y + 1, cnt))
  
  if x+1 < n:
    if v[x+1][y] != -1:
      ans = max(ans, solve(x + 1, y, 1) + v[x + 1][y])
    
    ans = max(ans, solve(x + 1, y, 0))
  
  return ans

for i in range(n):
  v.append([-1]*m)

for i in range(k):
  x,y,val = [int(x) for x in input().split()]
  x-=1
  y-=1
  v[x][y] = val

ans = solve(0,0,0)

if v[0][0] != -1:
  ans = max(ans, solve(0,0,1) + v[0][0])

print(ans)

Submission status: Runtime Error

Solution code:
from functools import lru_cache

n,m,k = [int(x) for x in input().split()]
v = []

@lru_cache(maxsize=1000000)
def solve(x, y, cnt):
  if x==n-1 and y == m-1:
    return 0
  
  ans = -1

  if y+1 < m:
    if cnt < 3 and v[x][y+1] != -1:
      ans = max(ans, solve(x, y + 1, cnt + 1) + v[x][y + 1])
    ans = max(ans, solve(x, y + 1, cnt))
  
  if x+1 < n:
    if v[x+1][y] != -1:
      ans = max(ans, solve(x + 1, y, 1) + v[x + 1][y])
    
    ans = max(ans, solve(x + 1, y, 0))
  
  return ans

for i in range(n):
  v.append([-1]*m)

for i in range(k):
  x,y,val = [int(x) for x in input().split()]
  x-=1
  y-=1
  v[x][y] = val

ans = solve(0,0,0)

if v[0][0] != -1:
  ans = max(ans, solve(0,0,1) + v[0][0])

print(ans)

Submission status: Runtime Error

Solution code:
from functools import lru_cache

n,m,k = [int(x) for x in input().split()]
v = []

@lru_cache(maxsize=3000)
def solve(x, y, cnt):
  if x==n-1 and y == m-1:
    return 0
  
  ans = -1

  if y+1 < m:
    if cnt < 3 and v[x][y+1] != -1:
      ans = max(ans, solve(x, y + 1, cnt + 1) + v[x][y + 1])
    ans = max(ans, solve(x, y + 1, cnt))
  
  if x+1 < n:
    if v[x+1][y] != -1:
      ans = max(ans, solve(x + 1, y, 1) + v[x + 1][y])
    
    ans = max(ans, solve(x + 1, y, 0))
  
  return ans

for i in range(n):
  v.append([-1]*m)

for i in range(k):
  x,y,val = [int(x) for x in input().split()]
  x-=1
  y-=1
  v[x][y] = val

ans = solve(0,0,0)

if v[0][0] != -1:
  ans = max(ans, solve(0,0,1) + v[0][0])

print(ans)

Submission status: Runtime Error

Solution code:
from functools import lru_cache

n,m,k = [int(x) for x in input().split()]
v = []

@lru_cache(maxsize=100000)
def solve(x, y, cnt):
  if x==n-1 and y == m-1:
    return 0
  
  ans = -1

  if y+1 < m:
    if cnt < 3 and v[x][y+1] != -1:
      ans = max(ans, solve(x, y + 1, cnt + 1) + v[x][y + 1])
    ans = max(ans, solve(x, y + 1, cnt))
  
  if x+1 < n:
    if v[x+1][y] != -1:
      ans = max(ans, solve(x + 1, y, 1) + v[x + 1][y])
    
    ans = max(ans, solve(x + 1, y, 0))
  
  return ans

for i in range(n):
  v.append([-1]*m)

for i in range(k):
  x,y,val = [int(x) for x in input().split()]
  x-=1
  y-=1
  v[x][y] = val

ans = solve(0,0,0)

if v[0][0] != -1:
  ans = max(ans, solve(0,0,1) + v[0][0])

print(ans)

Submission status: Runtime Error

Solution code:
from functools import lru_cache

n,m,k = [int(x) for x in input().split()]
v = []

@lru_cache(maxsize=4000000)
def solve(x, y, cnt):
  if x==n-1 and y == m-1:
    return 0
  
  ans = -1

  if y+1 < m:
    if cnt < 3 and v[x][y+1] != -1:
      ans = max(ans, solve(x, y + 1, cnt + 1) + v[x][y + 1])
    ans = max(ans, solve(x, y + 1, cnt))
  
  if x+1 < n:
    if v[x+1][y] != -1:
      ans = max(ans, solve(x + 1, y, 1) + v[x + 1][y])
    
    ans = max(ans, solve(x + 1, y, 0))
  
  return ans

for i in range(n):
  v.append([-1]*m)

for i in range(k):
  x,y,val = [int(x) for x in input().split()]
  x-=1
  y-=1
  v[x][y] = val

ans = solve(0,0,0)

if v[0][0] != -1:
  ans = max(ans, solve(0,0,1) + v[0][0])

print(ans)

Submission status: Runtime Error

Solution code:
R, C, K = map(int, input().split())
item_lis = list(list(map(int, input().split())) for i in range(K))
item_map = [[0 for i in range(C)] for i in range(R)]
for i,j,k in item_lis:
  item_map[i-1][j-1] = k
inf = float("inf")
dp = [[[0 for i in range(4)] for i in range(C)] for i in range(R)]

def calc(x, y, z, lis1=item_map, lis2=dp):
  now_score = dp[x][y][z]
  dp1 = -inf
  dp2 = -inf
  dp3 = -inf
  dp4 = -inf
  if x+1 <= R-1:
    if z < 3:
      if lis1[x][y] != 0:
        dp1 = calc(x+1, y, 0)+lis1[x][y]+now_score
    dp2 = calc(x+1, y, 0)+now_score
      
  if y+1 <= C-1:
    if z < 3:
      if lis1[x][y] != 0:
        dp3 = calc(x, y+1, z+1)+lis1[x][y]+now_score
    dp4 = calc(x, y+1, z)+now_score
  
  if x == R-1 and y == C-1:
    if z < 3:
      new_score = now_score+lis1[x][y]
    else:
      new_score = now_score
  else:
    new_score = max(now_score, dp1, dp2, dp3, dp4)
  return new_score

ans = calc(0, 0, 0)
print(ans)

Submission status: Runtime Error

Solution code:

import sys
input = sys.stdin.buffer.readline

R, C, K = map(int,input().split())
RC = [[0] * (C+1) for _ in range(R+1)]

for _ in range(K):
    r, c, v = map(int,input().split())
    RC[r-1][c-1] = v


dp = [[[0] * (C+1) for i in range(R+1)] for j in range(4)]

dp[1][0][0] = RC[0][0]
for r in range(R):
    for c in range(C):
        for i in range(4):
            dp[i][r][c+1] = max(dp[i][r][c], dp[i][r][c+1])
            if i <= 2:
                dp[i+1][r][c+1] = max(dp[i][r][c] + RC[r][c+1], dp[i+1][r][c+1])
        dp[0][r+1][c] = max(max(dp[:][r][c]), dp[0][r+1][c])
        dp[1][r+1][c] = max(dp[1][r+1][c], dp[0][r+1][c] + RC[r+1][c])
        
print(max(dp[:][R-1][C-1]))

Submission status: Runtime Error

Solution code:
import sys
import queue

input_methods=['clipboard','file','key']
using_method=1
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 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] = qqq(0,cv[ci])
			
			ps = rc_to_s(ri, ci)
			if ps in dd:
				tv = dd[ps]
				for iii in range(1,4):
					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 _ 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:
import sys, math, heapq





if(__name__ == "__main__"):

    R, C, K= map(int, input().strip().split() )
    dp = [  [0] * (C+1)  for _ in range(2) ] #[value]
    items_matrix = [ [0] * (C+1)  for _ in range(R+1) ]

    Flags_item = [False]*(C+1)

    for i in range(K):
        item = list( map(int, input().strip().split() ) ) #[r, c, value] #y, x
        items_matrix[ item[0] ][ item[1] ] = item[2]
        Flags_item[ item[0] ] = True
    # print(items_matrix)
    r_old = 0
    r_new = 0
    for r in range(1, R+1): #縦
        used = [0, 0, 0]
        r_old = r_new
        r_new = r&1
        #横, 3まで

        if(Flags_item[r]==False):
            for c in range(1, C+1):
                dp[r_new][c] = dp[r_old][c]
            continue

        c = 1
        while(c < C+1):
            if(items_matrix[r][c]>0):
                if(dp[r_new][c-1]-used[0] > dp[r_old][c]):
                    minv = heapq.heappop(used)
                    dp[r_new][c] = dp[r_new][c-1]-minv + items_matrix[r][c]
                    heapq.heappush(used, items_matrix[r][c])
                elif(dp[r_new][c-1] > dp[r_old][c] + items_matrix[r][c]):
                    dp[r_new][c] = dp[r_new][c-1]
                else:
                    dp[r_new][c] = dp[r_old][c] + items_matrix[r][c]
                    used = [0, 0, items_matrix[r][c]]
                c += 1
            else:
                while(c < C+1 and items_matrix[r][c]==0):
                    if(dp[r_old][c] <dp[r_new][c-1]):
                        dp[r_new][c] = dp[r_new][c-1]
                    else:
                        dp[r_new][c] = dp[r_old][c]
                        used = [0, 0, 0]
                    c += 1





    print(dp[r_new][-1])

Submission status: Runtime Error

Solution code:
import numpy as np
#a = np.zeros((2, 3, 4), dtype=int)
R, C, K = map(int, input().split())
goods = np.zeros((R+1, C+1), dtype=int)
for i in range(1, K + 1):
    _r, _c, _v = map(int, input().split())
    goods[_r][_c] = _v
#dp = [[[0] * 4 for i in range(C + 1)] for j in range(R + 1)]
dp = np.zeros((R+1, C+1, 4), dtype=int)
dp[1][1][1] = goods[1][1]
for i in range(1, R + 1):
    for j in range(1, C + 1):
        dp[i][j][0] = max(max(dp[i-1][j]), dp[i][j-1][0])
        if goods[i][j] != 0:
            dp[i][j][1] = max(dp[i][j][1], max(max(dp[i - 1][j]), dp[i][j - 1][0]) + goods[i][j], dp[i][j-1][1])
            dp[i][j][2] = max(dp[i][j][2], dp[i][j - 1][1] + goods[i][j], dp[i][j-1][2])
            dp[i][j][3] = max(dp[i][j][3], dp[i][j - 1][2] + goods[i][j], dp[i][j-1][3])
        else:
            dp[i][j][1] = max(dp[i][j][1], dp[i][j-1][1])
            dp[i][j][2] = max(dp[i][j][2], dp[i][j-1][1])
            dp[i][j][3] = max(dp[i][j][3], dp[i][j-1][1])
print(max(dp[R][C]))
#print(dp)

Submission status: Runtime Error

Solution code:
# 入力
R, C, K = map(int, input().split())
point_map = [[0 for _ in range(C+1)] for _ in range(R+1)]
max_point = [[[0 for _ in range(4)] for _ in range(C + 1)]
             for _ in range(R + 1)]
maxmax_point = [[0 for _ in range(C + 1)] for _ in range(R + 1)]


for i in range(K):
    _r, _c, _k = map(int, input().split())
    point_map[_r][_c] = _k

for i in range(1, R+1):
    itemss = [[]]
    im = i-1
    for j in range(1, C + 1):
        jm = j - 1
        mxi = max_point[i]
        mxij = mxi[j]
        mxijm = mxi[jm]
        point = point_map[i][j]
        mxij[0] = max(
            mxijm[0], maxmax_point[im][j])
        if point == 0:
            mxij[1] = mxijm[1]
            mxij[2] = mxijm[2]
            mxij[3] = mxijm[3]
        else:
            itemss = [[]] + [items + [point]
                             for items in itemss]  # items[1] アイテム一つ
            itemss_len = len(itemss)
            #print(i, j, itemss)

            mxij[1] = max(
                mxijm[0] + point, maxmax_point[i - 1][j]+point)
            mxij[2] = mxijm[1] + point

            if itemss_len > 4:
                items = itemss[4]  # 4 こアイテムがあるやつ
                del_item = min(items)
                items.remove(del_item)
                sa = mxijm[3]-del_item
                if sa > mxijm[2]:
                    mxij[3] = sa + point
                    itemss = itemss[:3] + items
                else:
                    mxij[3] = mxijm[2] + point
                    itemss = itemss[:4]
            else:
                mxij[3] = mxijm[2] + point

            # print(i, j, itemss)

        # [print(i, j, n, mxij[n])
        # for n in range(len(mxij))]
        maxmax_point[i][j] = max(mxij)
        #print(i, j, maxmax_point[i][j])

print(maxmax_point[R][C])

Submission status: Runtime Error

Solution code:
R,C,K=map(int,input().split())
r,m=range,max
G=[[0]*(C+1)for i in r(R+1)]
for i in'_'*K:r,c,v=map(int,input().split());G[r][c]=v
F=[[[0]*(C+1)for i in r(R+1)]for i in r(4)]
for r in r(1,R+1):
	for x in r(1,4):
		for c in r(1,C+1):F[x][r][c]=m(F[x-1][r][c-1]+G[r][c],F[x][r][c-1],(x<2)*(G[r][c]+m(F[1][r-1][c],F[2][r-1][c],F[3][r-1][c])))
print(m(F[1][R][C],F[2][R][C],F[3][R][C]))

Submission status: Runtime Error

Solution code:
import sys
import math
import collections
import bisect
import itertools


import numpy as np
import numba
from numba import njit, b1, i4, i8, f8

sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))


# ===CODE===

@njit((i8, i8, i8, i8[:]), cache=True)
def main():
    r, c, k = ns()

    mat = [[0 for _ in range(c + 1)] for __ in range(r + 1)]
    for _ in range(k):
        x, y, v = ns()
        x, y = x - 1, y - 1
        mat[x][y] = v

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

    for i in range(r):
        ndp = [[0] * 4 for _ in range(c + 1)]
        for j in range(c):
            for n in range(2, -1, -1):
                dp[j][n + 1] = max(dp[j][n + 1], dp[j][n] + mat[i][j])

            ndp[j][0] = max(dp[j])
            for n in range(4):
                dp[j + 1][n] = max(dp[j + 1][n], dp[j][n])
        dp = ndp

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

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
import math
import collections
import bisect
import itertools
import numba
from numba import njit, b1, i4, i8, f8

# import numpy as np

sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))


# ===CODE===

@njit((i8, i8, i8, i8[:]), cache=True)
def main():
    r, c, k = ns()

    mat = [[0 for _ in range(c + 1)] for __ in range(r + 1)]
    for _ in range(k):
        x, y, v = ns()
        x, y = x - 1, y - 1
        mat[x][y] = v

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

    for i in range(r):
        ndp = [[0] * 4 for _ in range(c + 1)]
        for j in range(c):
            for n in range(2, -1, -1):
                dp[j][n + 1] = max(dp[j][n + 1], dp[j][n] + mat[i][j])

            ndp[j][0] = max(dp[j])
            for n in range(4):
                dp[j + 1][n] = max(dp[j + 1][n], dp[j][n])
        dp = ndp

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

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
import math
import collections
import bisect
import itertools
import numba
from numba import njit, b1, i4, i8, f8

# import numpy as np

sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))


# ===CODE===

@njit((i8, i8, i8, i8[:]), cache=True)
def main():
    r, c, k = ns()

    mat = [[0] * (c + 1)] * (r + 1)
    for _ in range(k):
        x, y, v = ns()
        x, y = x - 1, y - 1
        mat[x][y] = v

    dp = [[0] * 4] * (c + 1)

    for i in range(r):
        ndp = [[0] * 4] * (c + 1)
        for j in range(c):
            for n in range(2, -1, -1):
                dp[j][n + 1] = max(dp[j][n + 1], dp[j][n] + mat[i][j])

            ndp[j][0] = max(dp[j])
            for n in range(4):
                dp[j + 1][n] = max(dp[j + 1][n], dp[j][n])
        dp = ndp

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


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# 入力
R, C, K = map(int, input().split())
point_map = [[0 for _ in range(C+1)] for _ in range(R+1)]
max_point = [[[0 for _ in range(4)] for _ in range(C + 1)]
             for _ in range(R + 1)]
maxmax_point = [[0 for _ in range(C + 1)] for _ in range(R + 1)]


for i in range(K):
    _r, _c, _k = map(int, input().split())
    point_map[_r][_c] = _k

for i in range(1, R+1):
    itemss = [[]]
    im = i-1
    for j in range(1, C + 1):
        jm = j - 1
        mxi = max_point[i]
        mxij = mxi[j]
        mxijm = mxi[jm]
        point = point_map[i][j]
        mxij[0] = max(
            mxijm[0], maxmax_point[im][j])
        if point == 0:
            mxij[1] = mxijm[1]
            mxij[2] = mxijm[2]
            mxij[3] = mxijm[3]
        else:
            itemss = [[]] + [items + [point]
                             for items in itemss]  # items[1] アイテム一つ
            itemss_len = len(itemss)
            #print(i, j, itemss)

            mxij[1] = max(
                mxijm[0] + point, maxmax_point[i - 1][j]+point)
            mxij[2] = mxijm[1] + point

            if itemss_len > 4:
                items = itemss[4]  # 4 こアイテムがあるやつ
                del_item = min(items)
                items.remove(del_item)
                sa = mxijm[3]-del_item
                if sa > mxijm[2]:
                    mxij[3] = sa + point
                    itemss = itemss[:3] + items
                else:
                    mxij[3] = mxijm[2] + point
                    itemss = itemss[:4]
            else:
                mxij[3] = mxijm[2] + point

        # [print(i, j, n, mxij[n])
        # for n in range(len(mxij))]
        maxmax_point[i][j] = max(mxij)
        #print(i, j, maxmax_point[i][j])

print(maxmax_point[R][C])

Submission status: Runtime Error

Solution code:
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7

def recur(row,col):
    if dp[row][col]:
        return dp[row][col]
    l=[]
    if row==r:
        l=sorted(mat[row][col:],reverse=True)
        dp[row][col]=sum(l[:3])
    else:
        for i in range(col,c+1):
            l.append(mat[row][i])
            l.sort(reverse=True)
            dp[row][col]=max(dp[row][col],sum(l[:3])+recur(row+1,i))
    return dp[row][col]

r,c,k=mdata()
mat=[[0 for i in range(c+1)] for j in range(r+1)]
for i in range(k):
    ri,ci,vi=mdata()
    mat[ri][ci]=vi
dp=[[0 for i in range(c+1)] for j in range(r+1)]
out(recur(1,1))

Submission status: Runtime Error

Solution code:
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7

def recur(row,col):
    if dp[row][col]:
        return dp[row][col]
    l=[]
    if row==r:
        l=sorted(mat[row][col:],reverse=True)
        dp[row][col]=sum(l[:3])
    else:
        for i in range(col,c+1):
            l.append(mat[row][i])
            l.sort(reverse=True)
            dp[row][col]=max(dp[row][col],sum(l[:3])+recur(row+1,i))
    return dp[row][col]

r,c,k=mdata()
mat=[[0 for i in range(c+1)] for i in range(r+1)]
for i in range(k):
    ri,ci,vi=mdata()
    mat[ri][ci]=vi
dp=[[0 for i in range(c+1)] for i in range(r+1)]
out(recur(1,1))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**8)
from collections import defaultdict
inf = 10**18
N = int(input())
S = []
C = []
for i in range(N):
    s,c = input().split()
    S.append(s)
    C.append(int(c))
    
d_l = defaultdict(lambda:inf)
def left(s1):
    res = inf
    if s1==s1[::-1]:
        return 0
    if d_l[s1] != inf:
        return d_l[s1]
    for i in range(N):
        s2 = S[i][::-1]
        c = C[i]
        if s1.startswith(s2):
            res = min(res,left(s1[len(s2):])+c)
        if s2.startswith(s1):
            res = min(res,right(s2[len(s1):])+c)
    d_l[s1] = res
    return res

d_r = defaultdict(lambda:inf)
def right(s2):
    res = inf
    if s2==s2[::-1]:
        return 0
    if d_r[s2] != inf:
        return d_r[s2]
    for i in range(N):
        s1 = S[i]
        c = C[i]
        if s1.startswith(s2):
            res = min(res,left(s1[len(s2):])+c)
        if s2.startswith(s1):
            res = min(res,right(s2[len(s1):])+c)
    d_r[s2] = res
    return res

ans = inf
for i in range(N):
    ans = min(ans,left(S[i])+C[i])

if ans == inf:
    ans = -1

print(ans)