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
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
            if j >= 1:
                val1 = dp[i][j-1][k]
            if k == 0 and i != 0:
                val2 = max(dp[i-1][j])
            if a[i][j] != 0:
                if k == 1 and i >= 1:
                    val3 = max(dp[i-1][j]) + 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, 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 = [[0 for i in range(C)] 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)] for j in range(R)]
    for i in range(R):
        if i == 0:
            #初期化
            d[0][0][1] = mylist[0][0]
            for k in range(1,4):
                d[0][0][k] = max(d[0][0][k], d[0][0][k-1])
            for j in range(1,C):
                temp = mylist[i][j]
                if temp != 0:
                    d[i][j][0] = d[i][j-1][0]
                    for k in range(1,4):
                        d[i][j][k] = max(d[i][j][k], d[i][j-1][k], d[i][j-1][k-1]+temp, d[i][j][k-1])
                else:
                    d[i][j] = d[i][j-1]
        else:
            #初期化
            d[i][0][0] = d[i-1][0][3]
            temp = mylist[i][0]
            for k in range(1,4):
                d[i][0][k] = d[i][0][0]+temp
            for j in range(1,C):
                temp = mylist[i][j]
                add = d[i-1][j][3]
                #0の場合
                d[i][j][0] = max(d[i][j-1][0], add)
                if temp != 0:
                    #1個の場合
                    d[i][j][1] = max(d[i][j-1][1], d[i][j-1][0]+temp, add+temp)
                    #2個の場合
                    d[i][j][2] = max(d[i][j-1][2], d[i][j-1][1]+temp)
                    #3個の場合
                    d[i][j][3] = max(d[i][j-1][3], d[i][j-1][2]+temp)
                    for k in range(1,4):
                        d[i][j][k] = max(d[i][j][k], d[i][j][k-1])
                else:
                    #1個以上の場合
                    for k in range(1,4):
                        d[i][j][k] = max(d[i][j-1][k], d[i][j][k-1])
    print(d[R-1][C-1][3])

if __name__ == "__main__":
    main()

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()
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:
def solve():
    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][k] = max(dp[i][j - 1][k], dp[i - 1][j][3])
            if (i, j) not in items:
                continue
            for k in range(3, 0, -1):
                dp[i][j][k] = max(dp[i][j][k], dp[i][j][k - 1] + items[(i, j)])
    return dp[R][C][3]


R, C, K, *rcv = map(int, open(0).read().split())

items = {}
for r, c, v in zip(*[iter(rcv)] * 3):
    items[(r, c)] = v

print(solve())

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def run_dp(R, C, dp, f):
  for r in range(1,R+1):
    for c in range(1,C+1):
      v = f[r-1][c-1]
      prevmax = dp[r-1,c].max()
      if v==0:
        dp[r,c,0] = max(prevmax, dp[r,c-1,0])
        dp[r,c,1:4] = dp[r,c-1,1:4].copy()
      else:
        dp[r,c,0] = max(prevmax, dp[r][c-1][0])
        dp[r,c,1] = max(dp[r,c-1,1], prevmax+v)
        dp[r,c,2] = max(dp[r,c-1,2], dp[r,c-1,1]+v)
        dp[r,c,3] = max(dp[r,c-1,3], dp[r,c-1,2]+v)
  print(dp[R,C].max())

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

f = [[0 for i in range(C)] for j in range(R)]
for i in range(K):
  r,c,v = map(int, input().split())
  f[r-1][c-1] = v
dp = np.zeros((R+1,C+1,4), dtype=int)
run_dp(R, C, dp, f)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def run_dp(R, C, dp, f):
  for r in range(1,R+1):
    for c in range(1,C+1):
      v = f[r-1][c-1]
      prevmax = dp[r-1][c].max()
      if v==0:
        dp[r][c][0] = max(prevmax, dp[r][c-1][0])
        dp[r][c][1:4] = dp[r][c-1][1:4].copy()
      else:
        dp[r][c][0] = max(prevmax, dp[r][c-1][0])
        dp[r][c][1] = max(dp[r][c-1][1], prevmax+v)
        dp[r][c][2] = max(dp[r][c-1][2], dp[r][c-1][1]+v)
        dp[r][c][3] = max(dp[r][c-1][3], dp[r][c-1][2]+v)
  print(dp[R][C].max())

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

f = [[0 for i in range(C)] for j in range(R)]
for i in range(K):
  r,c,v = map(int, input().split())
  f[r-1][c-1] = v
dp = np.zeros((R+1,C+1,4), dtype=int)
run_dp(R, C, dp, f)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def run_dp(R, C, dp, f):
  for r in range(1,R+1):
    for c in range(1,C+1):
      v = f[r-1][c-1]
      prevmax = dp[r-1][c].max()
      if v==0:
        dp[r][c][0] = max(prevmax, dp[r][c-1][0])
        dp[r][c][1] = dp[r][c-1][1]
        dp[r][c][2] = dp[r][c-1][2]
        dp[r][c][3] = dp[r][c-1][3]
      else:
        dp[r][c][0] = max(prevmax, dp[r][c-1][0])
        dp[r][c][1] = max(dp[r][c-1][1], prevmax+v)
        dp[r][c][2] = max(dp[r][c-1][2], dp[r][c-1][1]+v)
        dp[r][c][3] = max(dp[r][c-1][3], dp[r][c-1][2]+v)
  print(dp[R][C].max())

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

f = [[0 for i in range(C)] for j in range(R)]
for i in range(K):
  r,c,v = map(int, input().split())
  f[r-1][c-1] = v
dp = np.zeros((R+1,C+1,4), dtype=int)
run_dp(R, C, dp, f)

Submission status: Time Limit Exceeded

Solution code:
import sys
import queue
import copy

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

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

#+++++

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

		
	
	
	
	
#+++++
isTest=False

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

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

Submission status: Time Limit Exceeded

Solution code:
import bisect
import sys,io
import math
from collections import deque
from heapq import heappush, heappop

input = sys.stdin.buffer.readline

def sRaw():
    return input().rstrip("\r")


def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))

INF = 1 << 29

DIV = (10**9) + 7
#DIV = 998244353

def mod_inv_prime(a, mod=DIV):
    return pow(a, mod-2, mod)


def mod_inv(a, b):
    r = a
    w = b
    u = 1
    v = 0
    while w != 0:
        t = r//w
        r -= t*w
        r, w = w, r
        u -= t*v
        u, v = v, u
    return (u % b+b) % b


def CONV_TBL(max, mod=DIV):
    fac, finv, inv = [0]*max, [0]*max, [0]*max
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1
    for i in range(2, max):
        fac[i] = fac[i-1]*i % mod
        inv[i] = mod - inv[mod % i] * (mod//i) % mod
        finv[i] = finv[i-1]*inv[i] % mod

    class CONV:
        def __init__(self):
            self.fac = fac
            self.finv = finv
            pass

        def ncr(self, n, k):
            if(n < k):
                return 0
            if(n < 0 or k < 0):
                return 0
            return fac[n]*(finv[k]*finv[n-k] % DIV) % DIV

    return CONV()


def cumsum(As):
    s = 0
    for a in As:
        s += a
        yield s


sys.setrecursionlimit(200005)


def dijkstra(G,start=0):
    heap = []
    cost = [INF]*len(G)
    heappush(heap,(0,start))
    while len(heap)!=0:
        c,n = heappop(heap)
        if cost[n] !=INF:
            continue
        cost[n]=c
        for e in G[n]:
            ec,v = e
            if cost[v]!=INF:
                continue
            heappush(heap,(ec+c,v))
    return cost


def main():
    R,C,K = isRaw()
    mas = [[0 for _ in range(C)]for _ in range(R)]
    for k in range(K):
        r,c,v = isRaw()
        mas[r-1][c-1]=v
    dp = [[[0 for _ in range(4)]for _ in range(C)] for r in range(R)]
    dp[0][0][1]=mas[0][0]
    dp[0][0][2]=mas[0][0]
    dp[0][0][3]=mas[0][0]
    for r in range(R):
        for c in range(C):
            if r>0:
                dp[r][c][0] = max(dp[r][c][0],dp[r-1][c][-1] )
                dp[r][c][1] = max(dp[r][c][1],dp[r-1][c][-1]+mas[r][c])
                dp[r][c][2] = max(dp[r][c][2],dp[r-1][c][-1]+mas[r][c])
                dp[r][c][3] = max(dp[r][c][3],dp[r-1][c][-1]+mas[r][c])
            if c>0:
                dp[r][c][0] = max(dp[r][c][0],dp[r][c-1][0])
                dp[r][c][1] = max(dp[r][c][1], dp[r][c-1][1], dp[r][c-1][0]+mas[r][c])
                dp[r][c][2] = max(dp[r][c][2], dp[r][c-1][2], dp[r][c-1][1]+mas[r][c])
                dp[r][c][3] = max(dp[r][c][3], dp[r][c-1][3], dp[r][c-1][2]+mas[r][c])
            

    print(max([dp[-1][-1][ni] for ni in range(4)]))

main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

import numpy as np

R,C,K=map(int,input().split())
V=np.zeros([R,C])

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

DP=np.zeros([R,C,4])
if V[0,0]!=0:
    DP[0,0,1]=V[0,0]

for i in range(1,R):
    j=0
    DP[i,j,0]=DP[i-1,j,0]
    DP[i,j,1]=max(DP[i-1,j,0]+V[i,j],DP[i-1,j,1]+V[i,j],DP[i-1,j,2]+V[i,j],DP[i-1,j,3]+V[i,j])
    
for j in range(1,C):
    i=0
    DP[i,j,0]=DP[i,j-1,0]
    if V[i,j]==0:
        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]
    else:
        DP[i,j,1]=max(DP[i,j-1,1],DP[i,j-1,0]+V[i,j])
        DP[i,j,2]=max(DP[i,j-1,2],DP[i,j-1,1]+V[i,j])
        DP[i,j,3]=max(DP[i,j-1,3],DP[i,j-1,2]+V[i,j])


for i in range(1,R):
    for j in range(1,C):
        DP[i,j,0]=max(DP[i-1,j,0],DP[i-1,j,1],DP[i-1,j,2],DP[i-1,j,3],DP[i,j-1,0])
        if V[i,j]==0:
            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]
        else:
            DP[i,j,1]=max(DP[i,j-1,1],DP[i,j-1,0]+V[i,j],DP[i-1,j,0]+V[i,j],DP[i-1,j,1]+V[i,j],DP[i-1,j,2]+V[i,j],DP[i-1,j,3]+V[i,j])
            DP[i,j,2]=max(DP[i,j-1,1]+V[i,j],DP[i,j-1,2])
            DP[i,j,3]=max(DP[i,j-1,2]+V[i,j],DP[i,j-1,3])

ans=max(DP[R-1,C-1,:])
print(int(ans))

Submission status: Time Limit Exceeded

Solution code:
import bisect
import sys,io
import math
from collections import deque
from heapq import heappush, heappop

def sRaw():
    return input().rstrip("\r")


def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))

INF = 1 << 29

def make2d_arr(h, w, val=INF):
    return [[val for i in range(w)]for i in range(h)]

DIV = (10**9) + 7
#DIV = 998244353

def mod_inv_prime(a, mod=DIV):
    return pow(a, mod-2, mod)


def mod_inv(a, b):
    r = a
    w = b
    u = 1
    v = 0
    while w != 0:
        t = r//w
        r -= t*w
        r, w = w, r
        u -= t*v
        u, v = v, u
    return (u % b+b) % b


def CONV_TBL(max, mod=DIV):
    fac, finv, inv = [0]*max, [0]*max, [0]*max
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1
    for i in range(2, max):
        fac[i] = fac[i-1]*i % mod
        inv[i] = mod - inv[mod % i] * (mod//i) % mod
        finv[i] = finv[i-1]*inv[i] % mod

    class CONV:
        def __init__(self):
            self.fac = fac
            self.finv = finv
            pass

        def ncr(self, n, k):
            if(n < k):
                return 0
            if(n < 0 or k < 0):
                return 0
            return fac[n]*(finv[k]*finv[n-k] % DIV) % DIV

    return CONV()


def cumsum(As):
    s = 0
    for a in As:
        s += a
        yield s


sys.setrecursionlimit(200005)


def dijkstra(G,start=0):
    heap = []
    cost = [INF]*len(G)
    heappush(heap,(0,start))
    while len(heap)!=0:
        c,n = heappop(heap)
        if cost[n] !=INF:
            continue
        cost[n]=c
        for e in G[n]:
            ec,v = e
            if cost[v]!=INF:
                continue
            heappush(heap,(ec+c,v))
    return cost


def main():
    R,C,K = isRaw()
    mas = make2d_arr(R,C,0)
    for k in range(K):
        r,c,v = isRaw()
        mas[r-1][c-1]=v
    dp = [make2d_arr(C,4,0) for r in range(R)]
    dp[0][0][1]=mas[0][0]
    dp[0][0][2]=mas[0][0]
    dp[0][0][3]=mas[0][0]
    for r in range(R):
        for c in range(C):
            if r>0:
                dp[r][c][0] = max(dp[r][c][0],dp[r-1][c][-1] )
                dp[r][c][1] = max(dp[r][c][1],dp[r-1][c][-1]+mas[r][c])
                dp[r][c][2] = max(dp[r][c][2],dp[r-1][c][-1]+mas[r][c])
                dp[r][c][3] = max(dp[r][c][3],dp[r-1][c][-1]+mas[r][c])
            if c>0:
                dp[r][c][0] = max(dp[r][c][0],dp[r][c-1][0])
                dp[r][c][1] = max(dp[r][c][1], dp[r][c-1][1], dp[r][c-1][0]+mas[r][c])
                dp[r][c][2] = max(dp[r][c][2], dp[r][c-1][2], dp[r][c-1][1]+mas[r][c])
                dp[r][c][3] = max(dp[r][c][3], dp[r][c-1][3], dp[r][c-1][2]+mas[r][c])
            

    print(max([dp[-1][-1][ni] for ni in range(4)]))

main()

Submission status: Time Limit Exceeded

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

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    #各行では連続した区間
    #行ごとに見ないと話が進まん，降りるタイミぐは各列高々3000こ，来るタイミングも同様
    
    mod=10**9+7
    R,C,K=MI()
    S=[[0]*(C+1) for _ in range(R+1)]

    
    for i in range(K):
        r,c,v=MI()
        S[r][c]=v
        
        
    dp=[[[0]*4 for _ in range(C+1)]for i in range(R+1)]
    # dp[i][j][k]はi行j列まで見てその行でk個以下
    
    for i in range(R+1):
        for j in range(C+1):
            for k in range(3):
                #S(i,j)からの移動を考える
                
                #右へ移動，-,拾わない，拾う
                if j+1<=C:
                    dp[i][j+1][k+1]=max(dp[i][j+1][k+1],dp[i][j][k+1],dp[i][j][k]+S[i][j+1])
                
                #下へ
                if i+1<=R:
                    temp=0
                    for kk in range(4):
                        temp=max(temp,dp[i][j][kk])
                    dp[i+1][j][0]=temp
                    dp[i+1][j][1]=temp+S[i+1][j]
                
    ans=0
    for k in range(4):
        ans=max(ans,dp[-1][-1][k])
        
    # for i in range(R+1):
    #     print(dp[i])
        
    print(ans)
                
        
    

main()

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 = [[0 for i in range(C)] for j in range(R)]
    for i in range(K):
        a, b, c = MI()
        mylist[a-1][b-1] = c
    d = [[defaultdict(lambda:-float('inf')) for i in range(C)] for j in range(R)]
    for i in range(R):
        if i == 0:
            #初期化
            if mylist[0][0] != 0:
                d[0][0][0] = 0
                d[0][0][1] = mylist[0][0]
            else:
                d[0][0][0] = mylist[0][0]

            for j in range(1,C):
                if mylist[i][j] != 0:
                    d[i][j][0] = d[i][j-1][0]
                    for k in range(1,4):
                        d[i][j][k] = max(d[i][j-1][k], d[i][j-1][k-1]+mylist[i][j])
                else:
                    d[i][j] = d[i][j-1]
        else:
            #初期化
            if mylist[i][0] != 0:
                d[i][0][0] = max(d[i-1][0].values())
                d[i][0][1] = d[i][0][0]+mylist[i][0]
            else:
                d[i][0][0] = max(d[i-1][0].values())
            for j in range(1,C):
                if mylist[i][j] != 0:
                    #0個の場合
                    d[i][j][0] = max(d[i][j-1][0], max(d[i-1][j].values()))
                    #1個の場合
                    d[i][j][1] = max(d[i][j-1][1], d[i][j-1][0]+mylist[i][j], max(d[i-1][j].values())+mylist[i][j])
                    #2個の場合
                    d[i][j][2] = max(d[i][j-1][2], d[i][j-1][1]+mylist[i][j])
                    #3個の場合
                    d[i][j][3] = max(d[i][j-1][3], d[i][j-1][2]+mylist[i][j])
                else:
                    #0個の場合
                    d[i][j][0] = max(d[i][j-1][0], max(d[i-1][j].values()))
                    #1個以上の場合
                    for k in range(1,4):
                        d[i][j][k] = d[i][j-1][k]
    print(max(d[R-1][C-1].values()))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
def run():
    # sys.stdin.readline()
    import sys
    input = sys.stdin.readline
    r,c,k = map(int,input().split())
    t = [[0 for i in range(c)] for i in range(r)]
    for i in range(k):
        a,b,z = map(int,input().split())
        t[a-1][b-1] = z
    t = tuple(t)
    dp = [[[0 for i in range(c)]for i in range(r)]for i in range(4)]
    dp[0][0][0] = 0
    dp[1][0][0] = t[0][0]
    dp[2][0][0] = t[0][0]
    dp[3][0][0] = t[0][0]
    for i in range(r-1):
        dp[0][i+1][0] = dp[1][i][0]
        for j in range(1,4):
            dp[j][i+1][0] = dp[1][i][0]+t[i+1][0]
    for i in range(c-1):
        dp[0][0][i+1] = 0
        for j in range(1,4):
            dp[j][0][i+1] = max(dp[1][0][i],t[0][i+1])
        for j in range(2,4):
            dp[j][0][i+1] = max(dp[2][0][i],dp[1][0][i]+t[0][i+1])
        dp[3][0][i+1] = max(dp[3][0][i],dp[2][0][i]+t[0][i+1])
    for i in range(r-1):
        for j in range(c-1):
            u = max(dp[0][i+1][j],dp[3][i][j+1])
            for s in range(0,4):
                dp[s][i+1][j+1] =  u
            u = max(dp[0][i+1][j]+t[i+1][j+1],dp[1][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
            for s in range(1,4):
                dp[s][i+1][j+1] = u
            u = max(dp[1][i+1][j]+t[i+1][j+1],dp[2][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
            for s in range(2,4):
                dp[s][i+1][j+1] = u
            dp[3][i+1][j+1] = max(dp[2][i+1][j]+t[i+1][j+1],dp[3][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
    print(dp[3][r-1][c-1])
 
if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def exit(*argv, **kwarg):
    print(*argv, **kwarg)
    sys.exit()


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def a_int(): return int(read())


def ints(): return list(map(int, read().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque


'''
dp[i][j]...(0,0)からスタートして(i,j)に到達する経路のなかでの最大の価値
dp[i][j]=max(dp[i][j-1],dp[i-1][j]) + v[i][j]


dp[i][j][k] ... (0,0)からスタートして(i,j)に到達する経路のなかでi行目ですでにk(以下)個選んでいるときの最大の価値

遷移は、i,jのvを拾うときと拾わないときのmax
dp[i][j][k] = max(dp[i][j-1][k-1]+V[i,j], dp[i][j-1][k]
                  ) #k個のままのほうが価値が高いかk-1から拾ったほうが価値が高いか

上からの遷移 # 拾うか拾わないかでこうかな
dp[i][j][0]=max(dp[i][j-1][0],max_k(dp[i-1][j]))
dp[i][j][1]=max(dp[i][j-1][0],max_k(dp[i-1][j][k])+V[i][j])
'''

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

# dp = [[[0] * 4 for _ in ra(C)] for _ in ra(R)]
dp = []
for _ in ra(R):
    tmp = []
    for _ in ra(C):
        tmp.append([0] * 4)
    dp.append(tmp)

# dp[0][0][0] = 0
for k in ra(1, 4):
    dp[0][0][k] = V[0][0]
for j in ra(1, C):
    for k in ra(1, 4):
        dp[0][j][k] = max(dp[0][j - 1][k], dp[0][j - 1][k - 1] + V[0][j])

for i in ra(1, R):
    dp[i][0][0] = max(dp[i - 1][0])
    dp[i][0][1] = dp[i][0][0] + V[i][0]
    dp[i][0][2] = dp[i][0][0] + V[i][0]
    dp[i][0][3] = dp[i][0][0] + V[i][0]


for i in ra(1, R):
    for j in ra(1, C):
        ma = max(dp[i - 1][j])
        dp[i][j][0] = max(dp[i][j - 1][0],  # 左
                          ma)  # 上

        dp[i][j][1] = max(dp[i][j - 1][0] + V[i][j],  # 左から来て拾う
                          dp[i][j - 1][1],  # 拾わないほうが大きい場合もある
                          ma + V[i][j])  # 上から来て拾う

        dp[i][j][2] = max(dp[i][j - 1][1] + V[i][j], dp[i][j - 1][2])
        dp[i][j][3] = max(dp[i][j - 1][2] + V[i][j], dp[i][j - 1][3])


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

# print(*values, sep='\n')
# print(*dp, sep='\n')

# dp2 = [[-1] * C for _ in ra(R)]
# for i in ra(R):
#     for j in ra(C):
#         dp2[i][j] = max(dp[i][j])
# print(*dp2, sep='\n')

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

dp = [[[0 for _ in range(C)] for __ in range(R)] for ___ in range(4)]
ans = 0
for i in range(R):
  for j in range(C):
    dp[1][i][j] = max(dp[1][i][j],dp[0][i][j]+board[i][j])
    for k in range(4):
      if j>0:
        dp[k][i][j] = max(dp[k][i][j],dp[k][i][j-1])
      if j>0 and k>0:
        dp[k][i][j] = max(dp[k][i][j],dp[k-1][i][j-1]+board[i][j])
      if i>0:
        dp[0][i][j] = max(dp[0][i][j],dp[k][i-1][j])
        dp[1][i][j] = max(dp[1][i][j],dp[k][i-1][j]+board[i][j])
      ans = max(ans,dp[k][i][j])
#print(*board,sep='\n')
#print(*dp,sep='\n')
print(ans)

Submission status: Time Limit Exceeded

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

for i in range(1, R+1):
    for j in range(1, C+1):
        for k in range(4):
            for l in range(4):
                dp[0][i][j] = max(dp[0][i][j], dp[l][i-1][j])
                dp[1][i][j] = max(dp[1][i][j], dp[l][i-1][j] + T[i][j])
            dp[k][i][j] = max(dp[k][i][j], dp[k][i][j-1])
            if k >= 1:
                dp[k][i][j] = max(dp[k][i][j], dp[k-1][i][j-1] + T[i][j])
ans = 0
for k in range(4):
    ans = max(ans, dp[k][R][C])
print(ans)