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: Time Limit Exceeded

Solution code:
import sys, bisect, math, itertools, string, queue, copy
import numpy as np
import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input())
def inpm(): return map(int,input().split())
def inpl(): return list(map(int, input().split()))
def inpls(): return list(input().split())
def inplm(n): return list(int(input()) for _ in range(n))
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)]
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)])

r,c,k = inpm()
RCV = inpll(k)

inf=float("inf")
dp=[[[-inf for i in range(r+1)] for j in range(c+1)] for k in range(4)]

q = queue.Queue()
q.put((0,0,0,0))

fielditem = [[-1]*(c+1) for i in range(r+1)]
for rr,cc,vv in RCV:
    fielditem[rr-1][cc-1] = vv
field = [[[-1]*4 for i in range(c)] for k in range(r)]

while not q.empty():
    rr,cc,itemcnt,vv = q.get()

    if fielditem[rr][cc] != -1 and itemcnt < 3:
        field[rr][cc][itemcnt+1] = max(field[rr][cc][itemcnt+1],vv + fielditem[rr][cc])
        field[rr][cc][itemcnt] = max(field[rr][cc][itemcnt],vv)
        if rr < r-1:
            q.put((rr+1,cc,0,vv + fielditem[rr][cc]))
        if cc < c-1:
            q.put((rr,cc+1,itemcnt+1,vv + fielditem[rr][cc]))
            q.put((rr,cc+1,itemcnt,vv))
    else:
        field[rr][cc][itemcnt] = max(field[rr][cc][itemcnt],vv)
        if rr < r-1:
            q.put((rr+1,cc,0,vv))
        if cc < c-1:
            q.put((rr,cc+1,itemcnt,vv))

print(max(field[r-1][c-1]))

Submission status: Time Limit Exceeded

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


@jit(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: Time Limit Exceeded

Solution code:
import sys
import numpy as np
import numba as nb


@nb.jit(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: Time Limit Exceeded

Solution code:
import sys
import numpy as np
import numba as nb


@nb.jit
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: Time Limit Exceeded

Solution code:
from math import *
import fractions
import sys
import collections
import itertools
import pprint
from collections import deque
from heapq import *
input=sys.stdin.readline
R,C,K=map(int,input().split())
table=[[0]*C for _ in range(R)]
dp=[[[0]*4 for _ in range(C)] for _ in range(R)]
for i in range(K):
    r,c,v=map(int,input().split())
    table[r-1][c-1]=v
for i in range(R):
    for j in range(C):
        for k in range(2,-1,-1):
            dp[i][j][k+1]=max(dp[i][j][k+1],dp[i][j][k]+table[i][j])
        for k in range(4):
            if i<R-1:
                dp[i+1][j][0]=max(dp[i+1][j][0],dp[i][j][k])
            if j<C-1:
                dp[i][j+1][k]=max(dp[i][j+1][k],dp[i][j][k])
print(max(dp[R-1][C-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
def main():
    R, C, K = map(int, input().split())
    item_map = [[0]*C for _ in range(R)]

    for _ in range(K):
        ir, ic, iv = map(int, input().split())
        item_map[ir-1][ic-1] = iv
    dp = []
    for row in range(R):
        ls = []
        for col in range(C):
            ls.append([0, 0, 0, 0])
        dp.append(ls)

    for row in range(R):
        for col in range(C):
            item = item_map[row][col]
            if row>=1 and col>=1:
                M = max(
                    dp[row-1][col][0],
                    dp[row-1][col][1],
                    dp[row-1][col][2],
                    dp[row-1][col][3],
                    dp[row][col-1][0],
                )
                dp[row][col][0] = M
                
                dp[row][col][1] = dp[row][col-1][1]
                dp[row][col][2] = dp[row][col-1][2]
                dp[row][col][3] = dp[row][col-1][3]
                if item:
                    dp[row][col][1] = max(
                        M + item,
                        dp[row][col-1][1]
                        )
                    dp[row][col][2] = max(
                        dp[row][col-1][1] + item,
                        dp[row][col-1][2]
                        )
                    dp[row][col][3] = max(
                        dp[row][col-1][2] + item,
                        dp[row][col-1][3]
                        )
            elif row == 0 and col == 0:
                if item != 0:
                    dp[row][col][1] = item
                    continue
            elif row == 0:
                dp[row][col][0] = dp[row][col-1][0]
                dp[row][col][1] = dp[row][col-1][1]
                dp[row][col][2] = dp[row][col-1][2]
                dp[row][col][3] = dp[row][col-1][3]
                if item:
                    dp[row][col][1] = max(dp[row][col-1][1], dp[row][col-1][0] + item)
                    dp[row][col][2] = max(dp[row][col-1][2], dp[row][col-1][1] + item)
                    dp[row][col][3] = max(dp[row][col-1][3], dp[row][col-1][2] + item)
                continue
            elif col == 0:
                dp[row][col][0] = max(
                    dp[row-1][col][0], dp[row-1][col][1], dp[row-1][col][2], dp[row-1][col][3])
                
                if item:
                    dp[row][col][1] = dp[row][col][0] + item
                continue
    print(max(dp[R-1][C-1]))
main()

Submission status: Time Limit Exceeded

Solution code:
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

if __file__=="test.py":
    f = open("./in_out/input.txt", "r", encoding="utf-8")
    read = f.read
    readline = f.readline

def main():
    R, C, K = map(int, readline().split())
    
    L_INF = int(1e17)
    dp = [[[-L_INF for _ in range(4)] for _ in range(C+1)] for _ in range(R+1)]
    cell = [[0 for _ in range(C+1)] for _ in range(R+1)]
    
    for i in range(K):
        x, y, c = map(int, readline().split())
        cell[x-1][y-1] = 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])
 
    print(dp[R][C][3])

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

dp0 = [[0]*C for _ in range(R)]
dp1 = [[0]*C for _ in range(R)]
dp2 = [[0]*C for _ in range(R)]
dp3 = [[0]*C for _ in range(R)]

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

Submission status: Time Limit Exceeded

Solution code:
r,c,k=map(int,input().split())
P=[[0 for i in range(c+1)] for q in range(r+1)]

for i in range(k):
    nr,nc,nv=map(int,input().split())
    #nr,nc,nv=map(int,inp[i].split())
    #T[nr].append((nc,nv))
    P[nr][nc]=nv

dp=[[[0,0,0,0] for i in range(c+1)] for q in range(r+1)]

for i in range(1,r+1):
    for q in range(1,c+1):
        pri=P[i][q]
        dp[i][q][0]=max(dp[i-1][q][3],dp[i][q-1][0])
        dp[i][q][1]=max(dp[i][q-1][1],dp[i][q-1][0]+pri,dp[i][q][0]+pri)
        dp[i][q][2]=max(dp[i][q-1][2],dp[i][q-1][1]+pri,dp[i][q][1])
        dp[i][q][3]=max(dp[i][q-1][3],dp[i][q-1][2]+pri,dp[i][q][2])

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

Submission status: Time Limit Exceeded

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 = [[[-f_inf] * W for _ in range(H)] for _ in range(4)]
    dp[0][0][0] = 0
    for h in range(H):
        for w in range(W):
            # アイテムを取る場合
            for i in reversed(range(3)):
                if dp[i][h][w] >= 0:
                    dp[i + 1][h][w] = max(dp[i + 1][h][w], dp[i][h][w] + grid[h][w])
            # アイテムを取らない場合
            for i in range(4):
                if dp[i][h][w] >= 0:
                    if h + 1 < H:
                        dp[0][h + 1][w] = max(dp[0][h + 1][w], dp[i][h][w])
                    if w + 1 < W:
                        dp[i][h][w + 1] = max(dp[i][h][w + 1], dp[i][h][w])
    res = 0
    for i in range(4):
        res = max(res, dp[i][-1][-1])
    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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), dtype=int)
for i,j,k in item_lis:
  item_map[i-1,j-1] = k
  
dp = np.zeros((C+1, 4), dtype=int)
for i in range(R):
  new_dp = np.zeros((C+1, 4), dtype=int)
  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])

ans = max(dp[C-1,:])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
f=lambda:map(int,input().split())
R,C,K=f()
g=[[0]*(C+1) for _ in range(R+1)]
for _ in range(K):
  r,c,v=f()
  g[r][c]=v
dp=[[[0]*4 for _ in range(C+2)] for _ in range(R+2)]
for i in range(1,R+1):
  for j in range(1,C+1):
    for k in range(3,-1,-1):
      if k: dp[i][j][k]=max(dp[i][j][k],dp[i][j][k-1]+g[i][j])
      dp[i+1][j][0]=max(dp[i+1][j][0],dp[i][j][k])
      dp[i][j+1][k]=max(dp[i][j+1][k],dp[i][j][k])
print(max(dp[R][C][k] for k in range(4)))

Submission status: Time Limit Exceeded

Solution code:
f=lambda:map(int,input().split())
R,C,K=f()
g=[[0]*(C+1) for _ in range(R+1)]
for _ in range(K):
  r,c,v=f()
  g[r][c]=v
dp=[[[0]*4 for _ in range(C+2)] for _ in range(R+2)]
for i in range(1,R+1):
  for j in range(1,C+1):
    for k in range(3,-1,-1):
      if k: dp[i][j][k]=max(dp[i][j][k],dp[i][j][k-1]+ｇ[i][j])
      dp[i+1][j][0]=max(dp[i+1][j][0],dp[i][j][k])
      dp[i][j+1][k]=max(dp[i][j+1][k],dp[i][j][k])
print(max(dp[R][C][k] for k in range(4)))

Submission status: Time Limit Exceeded

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+5)] for j in range(n+5)]
for i in range(n):
    for j in range(m):
        for k in range(3)[::-1]:
            dp[i][j][k+1] = max(dp[i][j][k+1], dp[i][j][k] + value[i][j])
        for k in range(4):
            dp[i+1][j][0] = max(dp[i+1][j][0], dp[i][j][k])
            dp[i][j+1][k] = max(dp[i][j+1][k], dp[i][j][k])
print(max(dp[n-1][m-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
inpl = lambda: list(map(int,input().split()))
R, C, K = inpl()
N = 3
val = [[0]*(C+1) for r in range(R+1)]
for _ in range(K):
    r, c, v = inpl()
    val[r][c] = v

score = [[[0]*(N+1) for c in range(C+1)] for r in range(R+1)]
for r in range(1,R+1):
    for c in range(1,C+1):
        for n in range(N+1):
            if n == 0:
                score[r][c][0] = max(score[r-1][c][-1], score[r][c-1][0])
            elif val[r][c] == 0:
                score[r][c][n] = max(score[r][c-1][n],score[r][c][n-1])
            elif n == 1:
                score[r][c][1] = max(score[r-1][c][-1]+val[r][c],
                                     score[r][c-1][0]+val[r][c],
                                     score[r][c-1][1],
                                     score[r][c][0])
            else:
                score[r][c][n] = max(score[r][c-1][n-1]+val[r][c],
                                     score[r][c-1][n],
                                     score[r][c][n-1])

print(score[R][C][-1])

Submission status: Time Limit Exceeded

Solution code:
R, C, K = map(int, input().split())
dp = [[[0]*4 for _ in range(R+1)] for _ in range(C+1)]
val = [[0]*(R+1) for _ in range(C+1)]

for i in range(K):
    r, c, v = map(int, input().split())
    val[c][r] = v

for i in range(1, C+1):
    for j in range(1, R+1):
        dp[i][j][0] = max(max(dp[i][j-1]), dp[i-1][j][0])
        if val[i][j]>0:
            dp[i][j][1] = max(dp[i-1][j][0]+val[i][j], dp[i-1][j][1], max(dp[i][j-1])+val[i][j])
            dp[i][j][2] = max(dp[i-1][j][1]+val[i][j], dp[i-1][j][2])
            dp[i][j][3] = max(dp[i-1][j][2]+val[i][j], dp[i-1][j][3])
        else:
            dp[i][j][1] = dp[i-1][j][1]
            dp[i][j][2] = dp[i-1][j][2]
            dp[i][j][3] = dp[i-1][j][3]           
#print(dp)
print(max(dp[-1][-1]))

Submission status: Time Limit Exceeded

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):
        for dy,dx in [(1,0),(0,1)]:
            ny = oy + dy
            nx = ox + dx
            if 0 <= ny < n and 0 <= nx < m:
                nva = value[ny][nx]
                if dx: #　横移動
                    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)
                else: #縦
                    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: Time Limit Exceeded

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)]
q = deque()
q.append((0,0))
dp[0][0][1] = value[0][0]
for oy in range(n):
    for ox in range(m):
        for dy,dx in [(1,0),(0,1)]:
            ny = oy + dy
            nx = ox + dx
            if 0 <= ny < n and 0 <= nx < m:
                nva = value[ny][nx]
                if dx: #　横移動
                    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)
                else: #縦移動
                    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: Time Limit Exceeded

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)]
q = deque()
q.append([0,0])
dp[0][0][1] = value[0][0]
while q:
    oy,ox = q.popleft()
    for dy,dx in [(1,0),(0,1)]:
        ny = oy + dy
        nx = ox + dx
        if 0 <= ny < n and 0 <= nx < m:
            nva = value[ny][nx]
            if dx: #　横移動
                for k in range(4):
                    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)
            else: #縦
                dp[ny][nx][0] = max(dp[oy][ox])
                if nva:
                    dp[ny][nx][1] = dp[ny][nx][0] + nva
            q.append([ny,nx])
# pprint.pprint(dp)
print(max(dp[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

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

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

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

R,C,K = LI()
r,c,v = LIR(K,3)

a = [[0]*C for _ in range(R)]
for i in range(K):
    a[r[i]-1][c[i]-1] = v[i]

dp = [[[0]*4 for _ in range(C)] for _ in range(R)]
if a[0][0]:
    dp[0][0][1] = a[0][0]

for i in range(R):
    for j in range(C):
        upper_max = max(dp[i-1][j]) if i >= 1 else 0
        for k in range(4):
            if j >= 1:
                dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k])
            if k == 0 and i >= 1:
                dp[i][j][k] = max(dp[i][j][k],upper_max)
            if a[i][j] != 0:
                if k == 1 and i >= 1:
                    dp[i][j][k] = max(dp[i][j][k],upper_max+a[i][j])
                if k >= 1 and j >= 1:
                    dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k-1]+a[i][j])

print(max(dp[R-1][C-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import defaultdict, deque
from copy import deepcopy
    
input = sys.stdin.readline
def RD(): return input().rstrip()
def F(): return float(input().rstrip())
def I(): return int(input().rstrip())
def MI(): return map(int, input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float,input().split()))
def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]
def end_of_loop():raise StopIteration
    
    
def main():
    R, C, K = MI()
    mylist = [defaultdict(int) for j in range(R)]
    for i in range(K):
        a, b, c = MI()
        mylist[a-1][b-1] = c
    d = [[0] * 4 for i in range(C)]
    d2 = deepcopy(d)
    for i in range(R):
        if i == 0:
            #初期化
            d[0][1] = mylist[0][0]
            for k in range(1,4):
                d[0][k] = max(d[0][k], d[0][k-1])
            for j in range(1,C):
                temp = mylist[i][j]
                if temp != 0:
                    d[j][0] = d[j-1][0]
                    for k in range(1,4):
                        d[j][k] = max(d[j][k], d[j-1][k], d[j-1][k-1]+temp, d[j][k-1])
                else:
                    d[j] = d[j-1]
        else:
            #初期化
            next_d = deepcopy(d2)
            next_d[0][0] = d[0][3]
            temp = mylist[i][0]
            for k in range(1,4):
                next_d[0][k] = next_d[0][0]+temp
            for j in range(1,C):
                temp = mylist[i][j]
                add = d[j][3]
                #0の場合
                next_d[j][0] = max(next_d[j-1][0], add)
                if temp != 0:
                    #1個の場合
                    next_d[j][1] = max(next_d[j-1][1], next_d[j-1][0]+temp, add+temp)
                    #2個の場合
                    next_d[j][2] = max(next_d[j-1][2], next_d[j-1][1]+temp)
                    #3個の場合
                    next_d[j][3] = max(next_d[j-1][3], next_d[j-1][2]+temp)
                    for k in range(1,4):
                        next_d[j][k] = max(next_d[j][k], next_d[j][k-1])
                else:
                    #1個以上の場合
                    for k in range(1,4):
                        next_d[j][k] = max(next_d[j-1][k], next_d[j][k-1])
            d = next_d
    print(d[C-1][3])

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

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

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

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

R,C,K = LI()
r,c,v = LIR(K,3)

a = [[0]*C for _ in range(R)]
for i in range(K):
    a[r[i]-1][c[i]-1] = v[i]

dp = [[[0]*4 for _ in range(C)] for _ in range(R)]
if a[0][0]:
    dp[0][0][1] = a[0][0]

for i in range(R):
    for j in range(C):
        upper_max = max(dp[i-1][j]) if i >= 1 else 0
        for k in range(4):
            if i == j == 0:
                continue
            val1 = 0
            val2 = 0
            val3 = 0
            val4 = 0
            if j >= 1:
                val1 = dp[i][j-1][k]
            if k == 0 and i >= 1:
                val2 = upper_max
            if a[i][j] != 0:
                if k == 1 and i >= 1:
                    val3 = upper_max + a[i][j]
                if k >= 1 and j >= 1:
                    val4 = dp[i][j-1][k-1] + a[i][j]
            dp[i][j][k] = max(val1,val2,val3,val4)

print(max(dp[R-1][C-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

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

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

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

R,C,K = LI()
r,c,v = LIR(K,3)

a = [[0]*C for _ in range(R)]
for i in range(K):
    a[r[i]-1][c[i]-1] = v[i]

dp = [[[0]*4 for _ in range(C)] for _ in range(R)]
if a[0][0]:
    dp[0][0][1] = a[0][0]

for i in range(R):
    for j in range(C):
        for k in range(4):
            if i == j == 0:
                continue
            val1 = 0
            val2 = 0
            val3 = 0
            val4 = 0
            upper_max = max(dp[i-1][j]) if i >= 1 else 0
            if j >= 1:
                val1 = dp[i][j-1][k]
            if k == 0 and i >= 1:
                val2 = upper_max
            if a[i][j] != 0:
                if k == 1 and i >= 1:
                    val3 = upper_max + a[i][j]
                if k >= 1 and j >= 1:
                    val4 = dp[i][j-1][k-1] + a[i][j]
            dp[i][j][k] = max(val1,val2,val3,val4)

print(max(dp[R-1][C-1]))