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:
# -*- 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

    memo = [[[0] * 4 for _ in range(C+1)] for __ in range(R+1)]

    for i in range(R):
        for j in range(C):
            for p in range(4):
                memo[i][j+1][p] = max(memo[i][j+1][p], memo[i][j][p])
                memo[i+1][j][0] = max(memo[i+1][j][0], memo[i][j][p])
            if V[i][j] != 0:
                for p in range(3):
                    memo[i][j+1][p+1] = max(memo[i][j+1][p+1], memo[i][j][p] + V[i][j])
                    memo[i+1][j][0] = max(memo[i+1][j][0], memo[i][j][p] + V[i][j])
    # from pprint import pprint
    return max(memo[R-1][C])



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:
R,C,K = map(int,input().split())
dp = [[[0 for l in range(4)] for _ in range(C+1)] for f in range(R+1)]
vl = [[0 for _ in range(C+1)] for f in range(R+1)]

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

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

Submission status: Time Limit Exceeded

Solution code:
r,c,k=map(int, input().split())
grid=[[0]*(c+1) for _ in range(r+1)]
for i in range(k):
    ri,ci,vi=map(int, input().split())
    grid[ri][ci]=vi

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

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])
            dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k])
        if grid[i][j]!=0:
            dp[i][j][1]=max(dp[i][j][1],dp[i-1][j][0]+grid[i][j])
            for k in range(1,4):
                dp[i][j][1]=max(dp[i][j][1],dp[i-1][j][k]+grid[i][j])
                dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k-1]+grid[i][j])

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

Submission status: Time Limit Exceeded

Solution code:
import sys

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

dp = [[[0]*4 for _ in range(C)] for _ in range(R+1)] # [r, c, とったアイテム]のvの最大値

for r in range(R-1, -1, -1):
    dp[r][C - 1][0] = dp[r + 1][C - 1][3]
    for i in range(1, 4):
        dp[r][C-1][i] = dp[r + 1][C-1][3]+values[r][C-1]
    for c in range(C-2, -1, -1):
        v = values[r][c]
        for i in range(4):
            if i == 0 or v==0:
                dp[r][c][i] = max([dp[r+1][c][3], dp[r][c+1][i]])
            else:
                dp[r][c][i] = max([dp[r + 1][c][3]+v, dp[r][c + 1][i], dp[r][c + 1][i-1] + v])

print(dp[0][0][3])

Submission status: Time Limit Exceeded

Solution code:
import heapq

r, c, k = map(int, input().split())
num = [[0 for i in range(c + 1)] for i in range(r + 1)]
for i in range(k):
    y, x, v = map(int, input().split())
    num[y][x] = v
score = [[[0 for i in range(4)] for i in range(c + 1)] for i in range(r + 1)]
for i in range(1, r + 1):
    for j in range(1, c + 1):
        for l in range(4):
            if l == 0:
                score[i][j][l] = max(max([score[i - 1][j][l] for l in range(4)]), score[i][j - 1][l])
            elif l == 1:
                score[i][j][l] = max(max([score[i - 1][j][l] for l in range(4)]) + num[i][j], score[i][j - 1][l], score[i][j - 1][l - 1] + num[i][j])
            else:
                score[i][j][l] = max(score[i][j - 1][l], score[i][j - 1][l - 1] + num[i][j])
print(max(score[r][c][l] for l in range(4)))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
r, c, k = map(int, input().split())
dp = [[[0 for _ in range(3)] for _ in range(c + 5)] for _ in range(r + 5)]
pt = [[0 for _ in range(c + 5)] for _ in range(r + 5)]

for i in range(k):
    r1, c1, v = map(int, input().split())
    dp[r1][c1][0] = v
    pt[r1][c1] = v

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

print(dp[r][c][2])

# デバッグ用
# for i in dp:
#     print(i)

Submission status: Time Limit Exceeded

Solution code:
def main():

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

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

    for i in range(R):
        for j in range(C):
            v = max(dp[i][j+1])
            u = 0
            if (i, j) in a: u = a[(i, j)]
            dp[i+1][j+1][0] = max(dp[i+1][j+1][0], v)
            dp[i+1][j+1][1] = max(dp[i+1][j+1][1], dp[i+1][j][1], dp[i+1][j][0] + u,  v + u)
            dp[i+1][j+1][2] = max(dp[i+1][j+1][2], dp[i+1][j][2], dp[i+1][j][1] + u )
            dp[i+1][j+1][3] = max(dp[i+1][j+1][3], dp[i+1][j][3], dp[i+1][j][2] + u )

    return max(dp[R][C])

if __name__ == '__main__':
    print(main())

Submission status: Time Limit Exceeded

Solution code:
import sys
input=lambda: sys.stdin.readline().rstrip()
r,c,k=map(int,input().split())
D=[[0]*c for _ in range(r)] 
for _ in range(k):
	ri,ci,v=map(int,input().split())
	ri-=1
	ci-=1
	D[ri][ci]=v


DP=[[[0]*4 for _ in range(c+1)] for i in range(r+1)]
for i in range(r):
	for j in range(c):
		v=D[i][j]
		if v!=0:
			DP[i][j][1]=max(DP[i-1][j])+v
		for ii in range(4):
			DP[i][j][0]=max(DP[i][j][0],DP[i-1][j][ii])
			if v!=0:
				DP[i][j][1]=max(DP[i][j][1],DP[i-1][j][ii]+v)
			DP[i][j][ii]=max(DP[i][j][ii],DP[i][j-1][ii])
			if v!=0 and ii!=0:
				DP[i][j][ii]=max(DP[i][j][ii],DP[i][j-1][ii-1]+v)
		
ans=max(DP[r-1][c-1])
print(ans)

Submission status: Time Limit Exceeded

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

def main():
    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**10]*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(4):
                        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)

if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def Rtest(T):
    case,err=0,0
    for i in range(T):
        inp=INP()
        a1,ls=naive(*inp)
        a2=solve(*inp)
        if a1!=a2:
            print((a1,a2),inp)
            err+=1
        case+=1
    print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in R(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**9)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()


show_flg=False
show_flg=True

ans=0


h,w,k=LI()
v=[[0]*(w+1) for i in range(h+1)]
for i in range(k):
    a,b,x=LI()
    v[a][b]=x

dp=[[0]*4 for i in range((w+1)*(h+1))]

for j in range(1,w+1):
    for i in range(1,h+1):
        up_max=max(dp[(i-1)*(w+1)+j][x]for x in range(4))
        dp[i*(w+1)+j][0]=up_max
        if v[i][j]!=0:
            dp[i*(w+1)+j][1]=max(dp[i*(w+1)+j][1],up_max+v[i][j])
        dp[i*(w+1)+j][0]=max(dp[i*(w+1)+j][0],dp[i*(w+1)+j-1][0])

        for x in range(1,4):
            dp[i*(w+1)+j][x]=max(dp[i*(w+1)+j][x],dp[i*(w+1)+j-1][x],dp[i*(w+1)+j-1][x-1]+v[i][j])

print(max(dp[h*(w+1)+w]))

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
rcv = 0
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:
            if c != 0:
                d = dp[r][c-1]
                for k in range(4):
                    if dp[r][c][k] < d[k]:
                        dp[r][c][k] = d[k]
                    # dp[r][c][k] = max(d[k], dp[r][c][k])
            if r != 0:
                dp[r][c][0] = max(max(dp[r-1][c]), dp[r][c][0])

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

Submission status: Time Limit Exceeded

Solution code:
def main():

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

    cur = [[0]*4 for _ in range(C+1)]
    prev = [[0]*4 for _ in range(C+1)]

    for i in range(R):
        cur, prev = prev, cur
        for j in range(C):
            for k in range(4): cur[j+1][k] = cur[j][k]
            v = max(prev[j+1])
            cur[j+1][0] = max(cur[j+1][0], v)
            if (i, j) in a:
                u = a[(i, j)]
                cur[j+1][1] = max(cur[j+1][1], cur[j][0] + u,  v + u)
                cur[j+1][2] = max(cur[j+1][2], cur[j][1] + u )
                cur[j+1][3] = max(cur[j+1][3], cur[j][2] + u )
        # print(cur)

    return max(cur[C])

if __name__ == '__main__':
    print(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

    memo = [[[0] * 4 for _ in range(C)] for __ in range(R)]
    def f(i, j, p):
        if i >= R or j >= C:
            return 0
        if memo[i][j][p] != 0:
            return memo[i][j][p]

        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])
        memo[i][j][p] = r
        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:
#!/usr/bin/env python3

import collections
import sys
input=sys.stdin.readline

r,c,k=map(int,input().split())
items=collections.defaultdict(int)
for _ in range(k):
    tr,tc,tv=map(int,input().split())
    items[(tr,tc)]=tv
dp=[[[0]*4 for _ in range(c+1)] for _ in range(r+1)]
for i in range(1,r+1):
    for j in range(1,c+1):
        tv=items[(i,j)]
        left_max=max(dp[i-1][j])
        #左から来るときは取った個数をリセットする
        dp[i][j][0]=max(dp[i][j-1][0],left_max)
        dp[i][j][1]=max(dp[i][j-1][1],dp[i][j-1][0]+tv,left_max+tv)        
        dp[i][j][2]=max(dp[i][j-1][2],dp[i][j-1][1]+tv)
        dp[i][j][3]=max(dp[i][j-1][3],dp[i][j-1][2]+tv)
print(max(dp[r][c]))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.buffer.readline
R,C,K = map(int,input().split())
goods = [[0]*(C+1) for _ in range(R+1)]
INF = 10**18
for i in range(K):
    ri,ci,vi = map(int,input().split())
    goods[ri][ci] = vi
DP = [[[-INF,-INF,-INF,-INF] for _ in range(C+1)] for _ in range(R+1)]
DP[1][1][0] = 0
if goods[1][1]:
    DP[1][1][1] = goods[1][1]
for j in range(1,C):
    DP[1][j+1][0] = 0
    if goods[1][j+1]:
        DP[1][j+1][1] = max(DP[1][j][1],DP[1][j][0]+goods[1][j+1])
        DP[1][j+1][2] = max(DP[1][j][2],DP[1][j][1]+goods[1][j+1])
        DP[1][j+1][3] = max(DP[1][j][3],DP[1][j][2]+goods[1][j+1])
    else:
        DP[1][j+1][1] = DP[1][j][1]
        DP[1][j+1][2] = DP[1][j][2]
        DP[1][j+1][3] = DP[1][j][3]
for i in range(1,R):
    DP[i+1][1][0] = max(DP[i][1])
    if goods[i+1][1]:
        DP[i+1][1][1] = DP[i+1][1][0] + goods[i+1][1]
for i in range(2,R+1):
    for j in range(2,C+1):
        DP[i][j][0] = max(max(DP[i-1][j]),DP[i][j-1][0])
        if goods[i][j]:
            DP[i][j][1] = max(DP[i][j][0]+goods[i][j],DP[i][j-1][1])
            DP[i][j][2] = max(DP[i][j-1][2],DP[i][j-1][1]+goods[i][j])
            DP[i][j][3] = max(DP[i][j-1][3],DP[i][j-1][2]+goods[i][j])
        else:
            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]
print(max(DP[R][C]))

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline
R, C, K = map(int, input().split())
rcv = [tuple(map(int, input().split())) for _ in range(K)]
values = [[0]*C for _ in range(R)]
for r, c, v in rcv:
    values[r-1][c-1] = v

dp = [[[0]*4 for _ in range(C)] for _ in range(R+1)] # [r, c, とったアイテム]のvの最大値

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

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

    memo = [[[0] * 4 for _ in range(C)] for __ in range(R)]

    @lru_cache(maxsize=None)
    def f(i, j, p):
        if i >= R or j >= C:
            return 0
        if memo[i][j][p] != 0:
            return memo[i][j][p]

        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])
        memo[i][j][p] = r
        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,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def Rtest(T):
    case,err=0,0
    for i in range(T):
        inp=INP()
        a1,ls=naive(*inp)
        a2=solve(*inp)
        if a1!=a2:
            print((a1,a2),inp)
            err+=1
        case+=1
    print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in R(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**9)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()


show_flg=False
show_flg=True

ans=0


h,w,k=LI()
v=[[0]*(w+1) for i in range(h+1)]
for i in range(k):
    a,b,x=LI()
    v[a][b]=x

dp=[[0]*4 for i in range((w+1)*(h+1))]

for i in range(1,h+1):
    for j in range(1,w+1):
        up_max=max(dp[(i-1)*(w+1)+j][x]for x in range(4))
        dp[i*(w+1)+j][0]=up_max
        if v[i][j]!=0:
            dp[i*(w+1)+j][1]=max(dp[i*(w+1)+j][1],up_max+v[i][j])
        dp[i*(w+1)+j][0]=max(dp[i*(w+1)+j][0],dp[i*(w+1)+j-1][0])

        for x in range(1,4):
            dp[i*(w+1)+j][x]=max(dp[i*(w+1)+j][x],dp[i*(w+1)+j-1][x],dp[i*(w+1)+j-1][x-1]+v[i][j])

print(max(dp[h*(w+1)+w]))

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

inf=10**16
h,w,k=MI()
aa=[[0]*w for _ in range(h)]
for _ in range(k):
    i,j,v=MI()
    aa[i-1][j-1]=v

dp=[[[-inf]*4 for _ in range(w)] for _ in range(h)]
dp[0][0][0]=0
for i in range(h):
    for j in range(w):
        for c in range(4):
            pre=dp[i][j][c]
            if pre==-inf:continue
            if i+1<h:dp[i+1][j][0]=max(dp[i+1][j][0],pre)
            if j+1<w:dp[i][j+1][c]=max(dp[i][j+1][c],pre)
            if aa[i][j]:
                if c<3 and i + 1 < h: dp[i + 1][j][0] = max(dp[i + 1][j][0], pre+aa[i][j])
                if c<3 and j + 1 < w: dp[i][j + 1][c+1] = max(dp[i][j + 1][c+1], pre+aa[i][j])

ans=-inf
for c in range(4):
    if c==3:ans=max(ans,dp[h-1][w-1][c])
    else:ans=max(ans,dp[h-1][w-1][c]+aa[h-1][w-1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys, math
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from itertools import combinations, permutations, product
from heapq import heappush, heappop
from functools import lru_cache
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 1000000007
sys.setrecursionlimit(1000000)

R, C, K = rl()
I = {}
for i in range(K):
	r, c, v = rl()
	I[(r, c)] = v

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

for i in range(R+1):
	for j in range(C+1):
		for m in range(4):
			ni, nj = i, j+1
			dp[ni][nj][m] = max(dp[ni][nj][m], dp[i][j][m])
			if m < 3 and (ni,nj) in I:
				dp[ni][nj][m+1] = max(dp[ni][nj][m+1], dp[i][j][m]+I[(ni,nj)])

			ni, nj = i+1, j
			dp[ni][nj][0] = max(dp[ni][nj][0], dp[i][j][m])
			if (ni, nj) in I:
				dp[ni][nj][1] = max(dp[ni][nj][1], dp[i][j][m]+I[(ni,nj)])
ans = 0
for m in range(4):
	ans = max(ans, dp[R][C][m])
print(ans)

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**10]*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(4):
                    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:
R,C,K = map(int,input().split())
dp = [[[0 for l in range(4)] for _ in range(C+1)] for f in range(R+1)]
vl = [[0 for _ in range(C+1)] for f in range(R+1)]

for i in range(K):
	r,c,v = map(int,input().split())
	vl[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][k] = max(dp[i][j][k], dp[i][j-1][k])
		dp[i][j][0] = max(dp[i][j][0], dp[i-1][j][0], dp[i-1][j][1], dp[i-1][j][2], dp[i-1][j][3])
		if vl[i][j] >= 1:
			for k in range(3, 0, -1):
				dp[i][j][k] = max(dp[i][j][k-1]+vl[i][j], dp[i][j][k])
		
print(max(dp[R][C][0], dp[R][C][1], dp[R][C][2], dp[R][C][3]))