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:
R, C, K = map(int, input().split())
dp = [[[0 for j in range(C+1)] for k in range(R+1)] for _ in range(4)]
# dp[r][c][j] :=r index c columns already j cnt
dp[0][0][0] = 0
D = [[0 for i in range(C+1)] for j in range(R+1)]

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

for i in range(R+1):
    for j in range(C+1):
        if D[i][j] > 0:
            v = D[i][j]
            M = max(dp[k][i-1][j] for k in range(4))
            dp[0][i][j] = max(dp[0][i][j-1], M)
            dp[1][i][j] = max(dp[0][i][j-1]+v, dp[1][i][j-1], M+v)
            dp[2][i][j] = max(dp[1][i][j-1]+v, dp[2][i][j-1])
            dp[3][i][j] = max(dp[2][i][j-1]+v, dp[3][i][j-1])

        else:
            M = max(dp[k][i-1][j] for k in range(4))
            dp[0][i][j] = max(dp[0][i][j-1], M)
            dp[1][i][j] = dp[1][i][j-1]
            dp[2][i][j] = dp[2][i][j-1]
            dp[3][i][j] = dp[3][i][j-1]

ans = 0
for i in range(4):
    ans = max(ans, dp[i][-1][-1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
R,C,K = map(int,input().split())
V = [[0]*C for i in range(R)]
dp = [[[0]*4 for i in range(C)] for i in range(R)]
for i in range(K):
    r,c,v = map(int,input().split())
    V[r-1][c-1] = v
dp[0][0][1] = V[0][0]
for i in range(R):
    for j in range(C):
        if i > 0:
            dp[i][j][0] = max(dp[i-1][j])
            if V[i][j] > 0:
                dp[i][j][1] = max(dp[i-1][j]) + V[i][j]
        if j > 0:
            for count in range(4):
                dp[i][j][count] = max(dp[i][j-1][count], dp[i][j][count])
            if V[i][j] > 0:
                for count in range(3):
                    dp[i][j][count+1] = max(dp[i][j-1][count] + V[i][j], dp[i][j][count+1])

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict as dd
R,C,K = map(int,input().split())
rcv = [tuple(map(int,input().split())) for _ in range(K)]
dp = [[[0]*4 for __ in range(C)] for _ in range(R)]

rc = dd(int)
for r,c,v in rcv:
    rc[(r-1,c-1)] = v

dp[0][0][1] = rc[(0,0)]
for r in range(R):
    for c in range(C):
        val = rc[(r,c)]
        if val != 0:
            for k in range(3):
                if c != 0:
                    dp[r][c][k+1] = max(dp[r][c-1][k] + val, dp[r][c][k+1])
                    dp[r][c][k] = max(dp[r][c-1][k], dp[r][c][k])
                if r != 0:
                    dp[r][c][1] = max(dp[r-1][c][k] + val, dp[r][c][1])
                    dp[r][c][0] = max(dp[r-1][c][k], dp[r][c][0])
            if c!=0:
                dp[r][c][3] = max(dp[r][c-1][3], dp[r][c][3])
            if r!=0:
                dp[r][c][1] = max(dp[r-1][c][3]+val, dp[r][c][1])
                dp[r][c][0] = max(dp[r-1][c][3], dp[r][c][0])
        else:
            for k in range(4):
                if c != 0:
                    dp[r][c][k] = max(dp[r][c-1][k], dp[r][c][k])
                if r != 0:
                    dp[r][c][0] = max(dp[r-1][c][k], dp[r][c][0])

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

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
def solve():
  R, C, K = map(int, input().split())
  item = [[0]*C for _ in range(R)]
  for i in range(K):
    r,c,v = map(int, input().split())
    item[r-1][c-1] = v
  dp = [[0]*4 for _ in range((R+1)*5000)]
  for i in range(1,R+1):
    for j in range(1,C+1):
      for k in range(4): #横から取らない
        dp[i*5000+j][k] = dp[i*5000+j-1][k]
      #上から取らない
      dp[i*5000+j][0] = max(dp[i*5000+j][0],max(dp[(i-1)*5000+j]))
      if item[i-1][j-1]>0:
        #上からとる
        dp[i*5000+j][1] = max(dp[i*5000+j][1],max(dp[(i-1)*5000+j])+item[i-1][j-1])
        for k in range(1,4): #横から取る
          dp[i*5000+j][k] = max(dp[i*5000+j][k],dp[i*5000+j-1][k-1]+item[i-1][j-1])
  ans = max(dp[R*5000+C])
  return ans
print(solve())

Submission status: Time Limit Exceeded

Solution code:
import bisect, copy, heapq, math, sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
def celi(a,b):
    return -(-a//b)
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

def main():
    r,c,k=map(int,input().split())
    rcv=[list(map(int,input().split())) for i in range(k)]

    dpm=[[0]*4 for i in range(c+1)]
    dpn=[[0]*4 for i in range(c+1)]

    dic={}
    for i in range(k):
        r1,c1,v=rcv[i]
        dic[(r1,c1)]=v

    for i in range(r):
        for j in range(c):
            dpn[j+1][0]=max(dpn[j+1][0],max(dpm[j+1]))
            if (i+1,j+1) in dic:
                for k in range(3)[::-1]:
                    dpn[j+1][k+1]=max(dpn[j+1][k]+dic[(i+1,j+1)],dpn[j][k]+dic[(i+1,j+1)])
            for k in range(4):
                dpn[j+1][k]=max(dpn[j+1][k],dpn[j][k])
        # print(dpn)
        dpm=copy.deepcopy(dpn)
        dpn=[[0]*4 for i in range(c+1)]
    print(max(dpm[-1]))

main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


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

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(R, C, K, RCV):

    V = [[0] * C for _ in range(R)]
    for r, c, v in RCV:
        V[r-1][c-1] = v

    @lru_cache(maxsize=None)
    def f(i, j, p):
        if i >= R or j >= C:
            return 0
        r = 0
        r = max(r, f(i+1, j, 0))
        r = max(r, f(i, j+1, p))
        if V[i][j] != 0 and p < 3:
            r = max(r, f(i+1, j, 0) + V[i][j])
            r = max(r, f(i, j+1, p+1) + V[i][j])
        return r
    return f(0, 0, 0)


def main():
    R, C, K = read_int_n()
    RCV = [read_int_n() for _ in range(K)]
    print(slv(R, C, K, RCV))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
# import heapq, functools, collections
# import math, random
# from collections import Counter, defaultdict

# available on Google, not available on Codeforces
# import numpy as np
# import scipy


def solve(items,R,C):  # fix inputs here
    console("----- solving ------")
    console(R,C)

    grid = [[0 for _ in range(C)] for _ in range(R)]

    for r,c,v in items:
        grid[r-1][c-1] = v

    # console(np.array(grid))  # PLEASE SILENCE
    console("\n\n")

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

    if grid[0][0] > 0:
        dp[0][0][1] = dp[0][0][0] + grid[0][0]

    for i in range(1,R):
        dp[i][0][0] = max(dp[i-1][0][0], dp[i-1][0][1])
        if grid[i][0] > 0:
            dp[i][0][1] = dp[i][0][0] + grid[i][0]

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

    # console(np.array(dp)[:,:,0])  # PLEASE SILENCE
    # console(np.array(dp)[:,0,:])  # PLEASE SILENCE
    # console(np.array(dp)[0,:,:])  # PLEASE SILENCE
    # console(np.array(dp))  # PLEASE SILENCE
    # console("\n\nPost")

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

    # console(np.array(dp)[:,:,0])  # PLEASE SILENCE
    # console(np.array(dp)[:,:,1])  # PLEASE SILENCE
    # console(np.array(dp)[:,:,2])  # PLEASE SILENCE
    # console(np.array(dp)[:,:,3])  # PLEASE SILENCE
    # console(np.array(dp))  # PLEASE SILENCE

    # return a string (i.e. not a list or matrix)
    return max(dp[R-1][C-1][k] for k in range(4))


def console(*args):  # the judge will not read these print statement
    # print('\033[36m', *args, '\033[0m', file=sys.stderr)
    return

# fast read all
inn = sys.stdin.readlines()

for case_num in [1]:
    # read line as a string
    # strr = input()

    # read line as an integer
    # k = int(input())
    
    # read one line and parse each word as a string
    # lst = input().split()

    # read one line and parse each word as an integer
    r,c,nrows = list(map(int,inn[0].split()))

    # read matrix and parse as integers (after reading read nrows)
    # lst = list(map(int,input().split()))
    # nrows = lst[0]  # index containing information, please change
    grid = []
    for t in range(1,nrows+1):
        grid.append(list(map(int,inn[t].split())))

    res = solve(grid,r,c)  # please change
    
    # Google - case number required
    # print("Case #{}: {}".format(case_num+1, res))

    # Codeforces - no case number required
    print(res)

Submission status: Time Limit Exceeded

Solution code:
import sys


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


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

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

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

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

    for i in range(R):
        for j in range(C):
            ct = field[i ][j ]
            if ct == 0:
                dp[i][j][0] = max(dp[i][j - 1][0], max(dp[i - 1][j]))

                for k in range(1, 4):
                    if j>0:
                        dp[i][j][k] = dp[i][j - 1][k]
            else:
                dp[i][j][0] = max(dp[i][j - 1][0], max(dp[i - 1][j]))
                dp[i][j][1] = max(ct + max(dp[i][j - 1][0], max(dp[i - 1][j])),dp[i][j-1][1])
                for k in range(2, 4):
                    if j >0:
                        dp[i][j][k] = max(dp[i][j - 1][k - 1] +ct,dp[i][j-1][k])

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

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
R, C, K = map(int, input().split())
dp = np.array([[[0 for i in range(4)] for j in range(C+1)]
               for k in range(R+1)])
# dp[r][c][j] :=r index c columns already j cnt
dp[0][0][0] = 0
D = np.array([[0 for i in range(C+1)] for j in range(R+1)])

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

for i in range(R+1):
    for j in range(C+1):
        if D[i][j] > 0:
            v = D[i][j]
            M = max(dp[i-1][j])
            dp[i][j][0] = max(dp[i][j-1][0], M)
            dp[i][j][1] = max(dp[i][j-1][0]+v, dp[i][j-1][1], M+v)
            dp[i][j][2] = max(dp[i][j-1][1]+v, dp[i][j-1][2])
            dp[i][j][3] = max(dp[i][j-1][2]+v, dp[i][j-1][3])

        else:
            M = max(dp[i-1][j])
            dp[i][j][0] = max(dp[i][j-1][0], M)
            dp[i][j][1] = dp[i][j-1][1]
            dp[i][j][2] = dp[i][j-1][2]
            dp[i][j][3] = dp[i][j-1][3]

ans = 0
for i in range(4):
    ans = max(ans, dp[-1][-1][i])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
r,c,k = map(int, sys.stdin.readline().rstrip("\n").split())
masu = [[0]*c for _ in range(r)]
for _ in range(k):
    ir,ic,iv = map(int, sys.stdin.readline().rstrip("\n").split())
    masu[ir-1][ic-1] = iv
masu_value = [[0]*c for _ in range(r)]
d = deque()
cp = (0,0,[0]*r,0)
d.append(cp)
if masu[0][0] != 0:
    masu_value[0][0] = masu[0][0]
    cp = (0,0,[1]+[0]*(r-1),masu[0][0])
    d.append(cp)
while d:
    cr,cc,ci,cv= d.popleft()
    for i in range(2):
        if i == 0:
            nr,nc = cr+1,cc
        else:
            nr,nc = cr, cc+1
        if nr < r and nc < c:
            masu_value[nr][nc] = max(masu_value[nr][nc],cv)
            ni,nv = ci[:],cv
            d.append((nr,nc,ni,nv))
            if masu[nr][nc] != 0:
                if ci[nr] <3:
                    masu_value[nr][nc] = max(masu_value[nr][nc],cv+masu[nr][nc])
                    ni,nv = ci[:],cv+masu[nr][nc]
                    ni[nr] = ci[nr]+1
                    d.append((nr,nc,ni,nv))
print(masu_value[r-1][c-1])

Submission status: Time Limit Exceeded

Solution code:
R, C, K = map(int, input().split())
dp = [[[0 for i in range(4)] for j in range(C+1)] for k in range(R+1)]
# dp[r][c][j] :=r index c columns already j cnt
dp[0][0][0] = 0
D = [[0 for i in range(C+1)] for j in range(R+1)]

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

for i in range(R+1):
    for j in range(C+1):
        if D[i][j] > 0:
            v = D[i][j]
            M = max(dp[i-1][j])
            dp[i][j][0] = max(dp[i][j-1][0], M)
            dp[i][j][1] = max(dp[i][j-1][0]+v, dp[i][j-1][1], M+v)
            dp[i][j][2] = max(dp[i][j-1][1]+v, dp[i][j-1][2])
            dp[i][j][3] = max(dp[i][j-1][2]+v, dp[i][j-1][3])

        else:
            M = max(dp[i-1][j])
            dp[i][j][0] = max(dp[i][j-1][0], M)
            dp[i][j][1] = dp[i][j-1][1]
            dp[i][j][2] = dp[i][j-1][2]
            dp[i][j][3] = dp[i][j-1][3]

ans = 0
for i in range(4):
    ans = max(ans, dp[-1][-1][i])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import sys

input = sys.stdin.readline

R, C, K = map(int, input().split())
table = [[None] * (C + 1) for _ in range(R + 1)]
for _ in range(K):
    r, c, v = map(int, input().split())
    table[r][c] = v

dp = np.zeros((R + 1, C + 1, 4), dtype=int)
for r in range(1, R + 1):
    for c in range(1, C + 1):
        m = dp[r - 1, c].max()
        dp[r, c] = np.maximum(m, dp[r, c - 1])
        if table[r][c] is not None:
            dp[r, c, 1:] = np.maximum(dp[r, c, 1:],
                                      np.maximum(m, dp[r, c - 1, :-1]) + table[r][c])

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

Submission status: Time Limit Exceeded

Solution code:
import bisect, copy, heapq, math, sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
def celi(a,b):
    return -(-a//b)
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

def main():
    r,c,k=map(int,input().split())
    rcv=[list(map(int,input().split())) for i in range(k)]

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

    dic={}
    for i in range(k):
        r1,c1,v=rcv[i]
        dic[(r1,c1)]=v

    for i in range(r):
        for j in range(c):
            dp[i+1][j+1][0]=max(dp[i+1][j+1][0],max(dp[i][j+1]))
            if (i+1,j+1) in dic:
                for k in range(3)[::-1]:
                    dp[i+1][j+1][k+1]=max(dp[i+1][j+1][k]+dic[(i+1,j+1)],dp[i+1][j][k]+dic[(i+1,j+1)])
            for k in range(4):
                dp[i+1][j+1][k]=max(dp[i+1][j+1][k],dp[i+1][j][k])
    print(max(dp[-1][-1]))

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
	return sys.stdin.buffer.readline()[:-1]

n, m, q = map(int, input().split())
g = [[0 for _ in range(m)] for _ in range(n)]
for _ in range(q):
	r, c, v = list(map(int, input().split()))
	g[r-1][c-1] = v

dp = [[[0 for _ in range(4)] for _ in range(m)] for _ in range(n)]
dp[0][0][1] = g[0][0]
for i in range(n):
	for j in range(m):
		if i > 0:
			dp[i][j][0] = max(dp[i][j][0], max(dp[i-1][j]))
		if j > 0:
			dp[i][j][0] = max(dp[i][j][0], dp[i][j-1][0])
			for k in range(1, 4):
				dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k])
				dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k-1] + g[i][j])
			if i > 0:
				dp[i][j][1] = max(dp[i][j][1], max(dp[i-1][j]) + g[i][j])
		if i > 0 and j == 0:
			dp[i][0][1] = max(dp[i][0][1], max(dp[i-1][0]) + g[i][j])

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
R, C, K = map(int, input().split())
dp = [[[0 for i in range(4)] for j in range(C+1)] for k in range(R+1)]
# dp[r][c][j] :=r index c columns already j cnt
dp[0][0][0] = 0
D = defaultdict(int)

for i in range(R):
    for j in range(C):
        D[(i, j)] = 0

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

for i in range(R+1):
    for j in range(C+1):
        if i==0 and j==0: continue
        if D[(i, j)] > 0:
            v = D[(i, j)]
            M = max(dp[i-1][j])
            dp[i][j][0] = max(dp[i][j-1][0], M)
            dp[i][j][1] = max(dp[i][j-1][0]+v, dp[i][j-1][1], M+v)
            dp[i][j][2] = max(dp[i][j-1][1]+v, dp[i][j-1][2])
            dp[i][j][3] = max(dp[i][j-1][2]+v, dp[i][j-1][3])

        elif D[(i, j)] == 0:
            M = max(dp[i-1][j])
            dp[i][j][0] = max(dp[i][j-1][0], M)
            dp[i][j][1] = dp[i][j-1][1]
            dp[i][j][2] = dp[i][j-1][2]
            dp[i][j][3] = dp[i][j-1][3]

ans = 0
for i in range(4):
    ans = max(ans, dp[-1][-1][i])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
R, C, K = map(int, input().split())
dp = [[[-float("inf") for i in range(4)] for j in range(C+1)] for k in range(R+1)]
# dp[r][c][j] :=r index c columns already j cnt
dp[0][0][0] = 0
D = defaultdict(int)

for i in range(R):
    for j in range(C):
        D[(i, j)] = 0

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

for i in range(R+1):
    for j in range(C+1):
        if i==0 and j==0: continue
        if D[(i, j)] > 0:
            v = D[(i, j)]
            M = max(dp[i-1][j])
            dp[i][j][0] = max(dp[i][j-1][0], M)
            dp[i][j][1] = max(dp[i][j-1][0]+v, dp[i][j-1][1], M+v)
            dp[i][j][2] = max(dp[i][j-1][1]+v, dp[i][j-1][2])
            dp[i][j][3] = max(dp[i][j-1][2]+v, dp[i][j-1][3])

        elif D[(i, j)] == 0:
            M = max(dp[i-1][j])
            dp[i][j][0] = max(dp[i][j-1][0], M)
            dp[i][j][1] = dp[i][j-1][1]
            dp[i][j][2] = dp[i][j-1][2]
            dp[i][j][3] = dp[i][j-1][3]

ans = 0
for i in range(4):
    ans = max(ans, dp[-1][-1][i])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]

import numpy as np
(r,c,_),*d = [list(map(int, s.split())) for s in open(0)]

dp = np.zeros([r+1,4], dtype=int)
d = sorted(d, key=lambda x:(x[1], x[0]))
for i, _, v in d:
    i -= 1
    if i > 0:
        dp[i,0] = max(dp[i,0], np.max(dp[:i]))
    dp[i,1:] = np.maximum(dp[i,1:], dp[i,:-1] + v)
print(np.max(dp))

Submission status: Time Limit Exceeded

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

dp = [[[0] * 4 for j in range(C)] for i in range(R)] 
#print(dp, item)


for i in range(R):
  for j in range(C):
    for k in range(4):
      if (i == 0) and (j == 0):
        continue
      else:
        if i == 0:
          dp[i][j][k] = dp[i][j - 1][k]
          #if (item[i][j] != 0) and (k != 0):
          #  dp[i][j][k] = max(dp[i][j][k], dp[i][j][k - 1] + item[i][j])  
        elif j == 0:
          dp[i][j][k] = dp[i - 1][j][3]
          #if (item[i][j] != 0) and (k != 0):
          #  dp[i][j][k] = max(dp[i][j][k], dp[i][j][k - 1] + item[i][j])           
        else:
          dp[i][j][k] = dp[i][j - 1][k]
          dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j][3])
          #if (item[i][j] != 0) and (k != 0):
          #  dp[i][j][k] = max(dp[i][j][k], dp[i][j][k - 1] + item[i][j])       
    #for k in range(3):
    #  dp[i][j][k + 1] = max(dp[i][j][k + 1], dp[i][j][k])
    
    for k in range(3):
          if (item[i][j] != 0):
            dp[i][j][3 - k] = max(dp[i][j][3 - k], dp[i][j][2 - k] + item[i][j])          

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

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
	return sys.stdin.buffer.readline()[:-1]

n, m, q = map(int, input().split())
g = [[0 for _ in range(m)] for _ in range(n)]
for _ in range(q):
	r, c, v = list(map(int, input().split()))
	g[r-1][c-1] = v

dp = [[[0 for _ in range(4)] for _ in range(m)] for _ in range(n)]
dp[0][0][1] = g[0][0]
for i in range(n):
	for j in range(m):
		if i > 0:
			for k in range(4):
				dp[i][j][0] = max(dp[i][j][0], dp[i-1][j][k])
		if j > 0:
			dp[i][j][0] = max(dp[i][j][0], dp[i][j-1][0])
			for k in range(1, 4):
				dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k])
		if g[i][j] > 0:
			if i > 0 and j == 0:
				dp[i][0][1] = max(dp[i][0][1], max(dp[i-1][0]) + g[i][j])
			elif j > 0:
				for k in range(1, 4):
					dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k-1] + g[i][j])
				if i > 0:
					dp[i][j][1] = max(dp[i][j][1], max(dp[i-1][j]) + g[i][j])

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

Submission status: Time Limit Exceeded

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

R, C, K = map(int, input().split())
INF = 10**18
dp = [[[-INF] * 4 for _ in range(C+1)] for _ in range(R+1)]
items = [[0] * (C+1) for _ in range(R+1)]
dp[1][0][0] = dp[0][1][0] = 0
for _ in range(K):
    r, c, v = map(int, input().split())
    items[r][c] = v
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 items[i][j]:
                dp[i][j][1] = max(dp[i][j][1], dp[i-1][j][k] + items[i][j])
            dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k])
            if items[i][j] and k:
                dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k-1] + items[i][j])
ans = max(dp[R][C])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect, copy, heapq, math, sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
def celi(a,b):
    return -(-a//b)
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

r,c,k=map(int,input().split())
rcv=[list(map(int,input().split())) for i in range(k)]

dp=[[[0]*(4) for i in range(c+1)] for j in range(r+1)]
# for i in range(r+1):
#     dp[i][0][0]=0
# for i in range(c+1):
#     dp[0][i][0]=0

dic={}
for i in range(k):
    r1,c1,v=rcv[i]
    dic[(r1,c1)]=v

for i in range(r):
    for j in range(c):
        dp[i+1][j+1][0]=max(dp[i+1][j+1][0],max(dp[i][j+1]))
        # if i==1 and j==3:
        #     print(dp[i+1][j+1])
        if (i+1,j+1) in dic:
            for k in range(3)[::-1]:
                # if dp[i+1][j][k]!=-1:
                dp[i+1][j+1][k+1]=max(dp[i+1][j+1][k]+dic[(i+1,j+1)],dp[i+1][j][k]+dic[(i+1,j+1)])
        # if i==1 and j==3:
        #     print(dp[i+1][j+1])
        for k in range(4):
            dp[i+1][j+1][k]=max(dp[i+1][j+1][k],dp[i+1][j][k])
print(max(dp[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]
import numpy as np
(r,c,_),*d = [list(map(int, s.split())) for s in open(0)]

dp = np.zeros([r+1,4], dtype=int)
d = sorted(d, key=lambda x:(x[1], x[0]))
for i, _, v in d:
    dp[i,0] = max(dp[i,0], np.max(dp[:i]))
    dp[i,1:] = np.maximum(dp[i,1:], dp[i,:-1] + v)
print(np.max(dp))

Submission status: Time Limit Exceeded

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

r,c,k=map(int,input().split())

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

dp=[[[-10**16]*4 for i in range(c)] for j in range(r)]

if item[0][0]==0:
    dp[0][0][0]=0
else:
    dp[0][0][0]=0
    dp[0][0][1]=item[0][0]

for i in range(r):
    for j in range(c):
        if j!=c-1:
            v=item[i][j+1]
            if v==0:
                for k in range(3):
                    dp[i][j+1][k]=max(dp[i][j][k],dp[i][j+1][k])
            else:
                dp[i][j+1][0]=max(dp[i][j][0],dp[i][j+1][0])
                dp[i][j+1][1]=max(dp[i][j][0]+v,dp[i][j][1],dp[i][j+1][1])
                dp[i][j + 1][2] = max(dp[i][j][1] + v, dp[i][j][2], dp[i][j + 1][2])
                dp[i][j + 1][3] = max(dp[i][j][2] + v, dp[i][j][3], dp[i][j + 1][3])
        if i!=r-1:
            v=item[i+1][j]
            if v==0:
                dp[i+1][j][0]=max(dp[i][j][0],dp[i][j][1],dp[i][j][2],dp[i][j][3],dp[i+1][j][0])
            else:
                dp[i + 1][j][0] = max(dp[i][j][0], dp[i][j][1], dp[i][j][2], dp[i][j][3], dp[i + 1][j][0])
                dp[i + 1][j][1] = max(dp[i][j][0]+v, dp[i][j][1]+v, dp[i][j][2]+v, dp[i][j][3]+v, dp[i + 1][j][1])

ans=max(dp[r-1][c-1][0],dp[r-1][c-1][1],dp[r-1][c-1][2],dp[r-1][c-1][3])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import io
import os

input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

R, C, K = [int(x) for x in input().split()]
grid = [[0 for c in range(C)] for r in range(R)]
for r, c, v in ((int(x) for x in input().split()) for i in range(K)):
    grid[r - 1][c - 1] = v


dp = [[[0 for i in range(3 + 1 + 1)] for c in range(C + 1)] for r in range(R + 1)]
dp2 = [[0 for c in range(C + 1)] for r in range(R + 1)]

inf = float("inf")
for r in range(R + 1):
    for c in range(C + 1):
        dp[r][c][-1] = -inf
for r in range(R):
    for c in range(C):
        for numTakenThisRow in range(3 + 1):
            best = max(
                dp[r][c - 1][numTakenThisRow],  # came from left
                dp2[r - 1][c],  # came from top, didn't take curr
                dp[r][c - 1][numTakenThisRow - 1]
                + grid[r][c],  # came from left, took curr
                dp2[r - 1][c] + grid[r][c]
                if numTakenThisRow == 1
                else 0,  # came from top, took curr
            )
            dp[r][c][numTakenThisRow] = best
        dp2[r][c] = max(dp[r][c][i] for i in range(3 + 1))
print(dp2[R - 1][C - 1])

Submission status: Time Limit Exceeded

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

score = [[[0]*4 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(4):
            if n == 0:
                score[r][c][0] = max(max(score[r-1][c]), score[r][c-1][0])
            elif val[r][c] == 0:
                score[r][c][n] = score[r][c-1][n]
            elif n == 1:
                score[r][c][1] = max(max(score[r-1][c])+val[r][c],
                                     score[r][c-1][0]+val[r][c],
                                     score[r][c-1][1]) 
            else:
                score[r][c][n] = max(score[r][c-1][n-1]+val[r][c],
                                     score[r][c-1][n])

print(max(score[R][C]))

Submission status: Time Limit Exceeded

Solution code:
import sys; input = sys.stdin.buffer.readline
INF = float("inf")

def getlist():
	return list(map(int, input().split()))


R, C, K = getlist()
items = [0] * (R * C)
for i in range(K):
	r, c, v = getlist()
	r -= 1; c -= 1
	items[r * C + c] = v

DP = [-INF] * (4 * R * C)
DP[0] = 0
DP[1] = items[0]

for r in range(1, R):
	DP[4 * C * r] = max(DP[4 * C * (r - 1)], DP[4 * C * (r - 1) + 1])
	DP[4 * C * r + 1] = max(DP[4 * C * (r - 1) + 1], DP[4 * C * (r - 1)]) + items[r * C]


for c in range(1, C):
	DP[4 * c] = DP[4 * (c - 1)]
	for itr in range(1, 4):
		DP[4 * c + itr] = max(DP[4 * (c - 1) + itr - 1] + items[c], DP[4 * (c - 1) + itr])

for r in range(1, R):
	for c in range(1, C):
		ind = 4 * C * (r - 1) + 4 * c
		prev = max(DP[ind], DP[ind + 1], DP[ind + 2], DP[ind + 3])
		val = items[r * C + c]
		DP[4 * C * r + 4 * c] = max(DP[4 * C * r + 4 * (c - 1)], prev)
		DP[4 * C * r + 4 * c + 1] = max(max(DP[4 * C * r + 4 * (c - 1)], prev) + val, DP[4 * C * r + 4 * (c - 1) + 1])
		for itr in range(2, 4):
			DP[4 * C * r + 4 * c + itr] = max(DP[4 * C * r + 4 * (c - 1) + itr - 1] + val, DP[4 * C * r + 4 * (c - 1) + itr])


ans = max(DP[-1], DP[-2], DP[-3], DP[-4])
print(ans)