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
input=sys.stdin.readline
def main():
    r,c,k=map(int,input().split())
    v=[[0]*c for _ in range(r)]
    for _ in range(k):
        ri,ci,a=map(int,input().split())
        ri-=1
        ci-=1
        v[ri][ci]=a
    dp=[[[0]*4 for _ in range(c)] for i in range(r)]
    #print(dp)
    if v[0][0]>0:
        dp[0][0][1]=v[0][0]
    for i in range(r):
        for j in range(c):
            if i>0:
                if v[i][j]>0:
                    for k in range(min(3,j+1)+1):
                        dp[i][j][1]=max(dp[i][j][1],dp[i-1][j][k]+v[i][j])
                for k in range(4):
                    dp[i][j][k]=max(dp[i][j][k],dp[i-1][j][k])
            if j>0:
                if v[i][j]>0:
                    for k in range(min(3,j+1)+1):
                        if k>0:
                            dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k-1]+v[i][j])
                for k in range(4):
                    dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k])
    #print(dp)
    print(max(dp[r-1][c-1]))
if __name__=="__main__":
    main()

Submission status: Time Limit Exceeded

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


r, c, k = map(int, input().split())
info = [list(map(int, input().split())) for i in range(k)]
INF = 10 ** 18

item = [[0] * c for i in range(r)]
for i, j, v in info:
    i -= 1
    j -= 1
    item[i][j] = v

OFFSET = (r + 1)
dp = [[-INF] * 4 for i in range((c + 1) * (r + 1))]
for i in range(r + 1):
    dp[i][0] = 0
for j in range(c + 1):
    dp[OFFSET * j][0] = 0
    
for i in range(r):
    for j in range(c):
        val = item[i][j]
        tmp11 = i + 1 + OFFSET * (j + 1)
        tmp = i + 1 + OFFSET * j
        tmp01 = i + OFFSET * (j + 1)

        dp[tmp11][0] = max(dp[tmp][0], dp[tmp01][0], dp[tmp01][1], dp[tmp01][2], dp[tmp01][3])
        dp[tmp11][1] = max(dp[tmp][1], dp[tmp][0] + val,  dp[tmp01][0] + val, dp[tmp01][1] + val, dp[tmp01][2] + val, dp[tmp01][3] + val)
        dp[tmp11][2] = max(dp[tmp][2], dp[tmp][1] + val)
        dp[tmp11][3] = max(dp[tmp][3], dp[tmp][2] + val)
          
print(max(dp[-1]))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

import sys
sys.setrecursionlimit(300000)


def solve(R: int, C: int, N: int, r: "List[int]", c: "List[int]", v: "List[int]", X):
    rr = sorted(list(set(r)))
    cc = sorted(list(set(c)))
    #print(rr, cc)
    rmap, cmap = {}, {}
    for i, vv in enumerate(rr):
        rmap[vv] = i
    for i, vv in enumerate(cc):
        cmap[vv] = i

    h, w = len(rr), len(cc)
    x = {}
    for i in range(N):
        rx, cx = rmap[r[i]], cmap[c[i]]
        if not rx in x:
            x[rx] = {}
        x[rx][cx] = v[i]

    dp = [[0] * (w + 1) for _ in range(h + 1)]
    #print(x)
    for i in range(h):
        for jj in range(w):
            tmp = [0, 0, 0]
            s = 0
            for j in range(jj, w):
                if i in x and j in x[i]:
                    if tmp[-1] < x[i][j]:
                        s += x[i][j] - tmp[-1] 
                        tmp[-1] = x[i][j]
                        tmp.sort(reverse=True)
                dp[i + 1][j] = max(dp[i + 1][j], dp[i][jj] + s)

    #print(dp)
    ret = 0
    for v in dp[h]:
        ret = max(ret, v)
    print(ret)
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    R = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    r = [int()] * (K)  # type: "List[int]"
    c = [int()] * (K)  # type: "List[int]"
    v = [int()] * (K)  # type: "List[int]"
    x = {}
    for i in range(K):
        r[i] = int(next(tokens)) - 1
        c[i] = int(next(tokens)) - 1
        v[i] = int(next(tokens))
        if not r[i] in x:
            x[r[i]] = {}
        x[r[i]][c[i]] = v[i]
    solve(R, C, K, r, c, v, x)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque, defaultdict
#deque(l), pop(), append(x), popleft(), appendleft(x)
#q.rotate(n)で → にn回ローテート
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations,product#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
from functools import reduce,lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printe(*x):print("## ",*x,file=sys.stderr)
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def binr(x): return bin(x)[2:]
def bitcount(x): #xは64bit整数
    x= x - ((x >> 1) & 0x5555555555555555)
    x= (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x= (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f 
    x+= (x >> 8); x+= (x >> 16); x+= (x >> 32) 
    return x & 0x7f

def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reverse=True)  #二個目の要素で降順並び替え

    #N = int(input())
    R,C,K = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    base=5000
    S=[]
    for i in range(K):
        r,c,v = map(int, input().split())
        r-=1
        c-=1
        S.append((r*base+c,v))

    S.sort(key=itemgetter(0))

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

    p=0
    
    for i in range(R):
        dpi=dp[i]
        for j in range(C):
            cv=0
            
            if p<K and i*base+j==S[p][0]:
                cv=S[p][1]
                p+=1
            if j>0:
                dpi[j]=copy(dpi[j-1])
            if i>0:
                dpi[j][0]=max(max(dp[i-1][j]),dpi[j][0])
            if cv!=0:
                for k in range(2,-1,-1):
                    dpi[j][k+1]=max(dpi[j][k]+cv,dpi[j][k+1])
                #printe(dp)
    print(max(dp[-1][-1]))



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy
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
  dp1 = [[0]*4 for _ in range(C+1)]
  dp2 = [[0]*4 for _ in range(C+1)]
  for i in range(1,R+1):
    for j in range(1,C+1):
      for k in range(4): #横から取らない
        dp2[j][k] = dp2[j-1][k]
      #上から取らない
      dp2[j][0] = max(dp2[j][0],max(dp1[j]))
      if item[i-1][j-1]>0:
        #上からとる
        dp2[j][1] = max(dp2[j][1],max(dp1[j])+item[i-1][j-1])
        for k in range(1,4): #横から取る
          dp2[j][k] = max(dp2[j][k],dp2[j-1][k-1]+item[i-1][j-1])
      dp1 = deepcopy(dp2)
  ans = max(dp2[-1])
  return ans
print(solve())

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
def main():
    r,c,k = map(int,input().split())
    lst = [[0]*c for _ in range(r)]
    for i in range(k):
        a,b,v = map(int,input().split())
        lst[a-1][b-1] = v
    dp = [[[0]*4 for i in range(c)] for j in range(r)]
    dp[0][0][1] = lst[0][0]
    for i in range(r):
        for j in range(c):
            x,y = i+1,j
            s = max(dp[i][j])
            if x < r:
                dp[x][y][0] = s
                if dp[x][y][1] < lst[x][y]+s:
                    dp[x][y][1] = lst[x][y]+s
            x,y = i,j+1
            if y < c:
                if dp[i][j][2] != 0:
                    if dp[x][y][3] < dp[i][j][3]:
                        dp[x][y][3] = dp[i][j][3]
                    if dp[x][y][3] < dp[i][j][2]+lst[x][y] and lst[x][y] != 0:
                        dp[x][y][3] = dp[i][j][2]+lst[x][y]
            
                if dp[i][j][1] != 0:
                    if dp[x][y][2] < dp[i][j][2]:
                        dp[x][y][2] = dp[i][j][2]
                    if dp[x][y][2] < dp[i][j][1]+lst[x][y] and lst[x][y] != 0:
                        dp[x][y][2] = dp[i][j][1]+lst[x][y]
            
                if dp[x][y][1] < dp[i][j][1]:
                    dp[x][y][1] = dp[i][j][1]
                if dp[x][y][1] < dp[i][j][0]+lst[x][y] and lst[x][y] != 0:
                    dp[x][y][1] = dp[i][j][0]+lst[x][y]

                if dp[x][y][0] < dp[i][j][0]:
                    dp[x][y][0] = dp[i][j][0]
    print(max(dp[-1][-1]))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
R, C, K = map(int, input().split())
rcvs = [tuple(map(int, input().split())) for _ in range(K)]

rcvs.sort(key = lambda t: t[1] * 30000 + t[0])

dp = [[0] * (R+1) for _ in range(4)]
index = 0
for c in range(C+1):
    while index < K and rcvs[index][1] == c:
        x, _, v = rcvs[index]
        if dp[3][x] < dp[2][x] + v:
            dp[3][x] = dp[2][x] + v
        if dp[2][x] < dp[1][x] + v:
            dp[2][x] = dp[1][x] + v
        if dp[1][x] < dp[0][x] + v:
            dp[1][x] = dp[0][x] + v
        index += 1
        for r in range(x, R):
            dp[0][r+1] = max(dp[0][r], dp[1][r], dp[2][r], dp[3][r])
        #print(dp)   
    
print(max(max(row) for row in dp))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque, defaultdict
#deque(l), pop(), append(x), popleft(), appendleft(x)
#q.rotate(n)で → にn回ローテート
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations,product#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
from functools import reduce,lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printe(*x):print("## ",*x,file=sys.stderr)
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def binr(x): return bin(x)[2:]
def bitcount(x): #xは64bit整数
    x= x - ((x >> 1) & 0x5555555555555555)
    x= (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x= (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f 
    x+= (x >> 8); x+= (x >> 16); x+= (x >> 32) 
    return x & 0x7f

def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reverse=True)  #二個目の要素で降順並び替え

    #N = int(input())
    R,C,K = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    base=5000
    S=[]
    for i in range(K):
        r,c,v = map(int, input().split())
        r-=1
        c-=1
        S.append((r*base+c,v))

    S.sort(key=itemgetter(0))

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

    p=0
    
    for i in range(R):
        dpi=dp[i]
        for j in range(C):
            cv=0
            
            if p<K and i*base+j==S[p][0]:
                cv=S[p][1]
                p+=1
            if j>0:
                for k in range(4):
                    dpi[j][k]=copy(dpi[j-1][k])
            if i>0:
                dpi[j][0]=max(max(dp[i-1][j]),dpi[j][0])
            if cv!=0:
                for k in range(2,-1,-1):
                    dpi[j][k+1]=max(dpi[j][k]+cv,dpi[j][k+1])
                #printe(dp)
    print(max(dp[-1][-1]))



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from collections import defaultdict

    r, c, k = map(int, readline().split())
    items = dict()
    for _ in range(k):
        row, col, value = map(int, readline().split())
        items[(row, col)] = value

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

    for row in range(1, r + 1):
        for col in range(1, c + 1):
            if (row, col) in items:
                value = items[(row, col)]
            else:
                value = 0
            for i in range(3):
                dp[row][col][1] = max(dp[row][col][1],dp[row][col][0] + value)
                dp[row][col][i + 1] = max(dp[row][col - 1][i + 1], dp[row][col - 1][i] + value)

            dp[row + 1][col][0] = max(dp[row][col])

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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# pypy
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
from collections import defaultdict

R, C, K = map(int, readline().split())
rcv = list(map(int, read().split()))
rr = rcv[::3]
cc = rcv[1::3]
vv = rcv[2::3]
rc2v = defaultdict(int)
for _r, _c, _v in zip(rr, cc, vv):
    rc2v[(_r-1, _c-1)] = _v


dp = [[[0]*4 for c in range(C)] for r in range(R)]
dp[0][0][1] = rc2v[(0, 0)]

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

for r in range(1, R):
    dp[r][0][0] = max(dp[r-1][0])
    if (r, 0) in rc2v:
        dp[r][0][1] = max(dp[r-1][0]) + rc2v[(r, 0)]

for r in range(1, R):
    for c in range(1, C):
        dp[r][c][0] = max(dp[r][c-1][0], max(dp[r-1][c]))
        for k in range(1, 4):
            dp[r][c][k] = max(dp[r][c-1][k], dp[r][c-1][k-1] + rc2v[(r, c)])
            
        dp[r][c][1] = max(dp[r][c][1], max(dp[r-1][c]) + rc2v[(r, c)])

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

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    
    r, c, k = map(int, input().split())
    tizu = [0 for _ in range(r * c)]
    for _ in range(k):
        rr, cc, v = map(int, input().split())
        tizu[(rr - 1) * c + (cc - 1)] = v
        
    dp = [[0, 0, 0, 0] for _ in range(c)]
    dp[0][1] = tizu[0]
    
    for i in range(r):
        for j in range(c):
            v = tizu[i * c + j]
            if i != 0:
                tmp = max(dp[j])
                dp[j] = [tmp, tmp + v, 0, 0]
            if j != 0:
                tmp0 = dp[j - 1][0]
                tmp1 = dp[j - 1][1]
                tmp2 = dp[j - 1][2]
                lst = [max(dp[j][0], tmp0), max(dp[j][1], tmp1, tmp0 + v), max(tmp2, tmp1 + v), max(dp[j - 1][3], tmp2 + v)]
                dp[j] = lst
    print(max(dp[-1]))
    
main()

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]
R,C,K=map(int,input().split())
l=[[[0]*4 for i in range(C)] for j in range(R)]
m=[[0]*C for i in range(R)]
for i in range(K):
    r,c,v=map(int,input().split())
    m[r-1][c-1]=v
if m[0][0]:
    l[0][0][1]=m[0][0]
for i in range(1,C):
    l[0][i][1]=max(l[0][i-1][1],m[0][i])
    l[0][i][2]=max(l[0][i-1][2],m[0][i]+l[0][i-1][1])
    l[0][i][3]=max(l[0][i-1][3],m[0][i]+l[0][i-1][2])
for i in range(1,R):
    l[i][0][1]=max(l[i-1][0])+m[i][0]
    for j in range(1,C):
        l[i][j][0]=max(l[i][j-1][0],max(l[i-1][j]))
        l[i][j][1]=max(l[i][j-1][0]+m[i][j],l[i][j-1][1],max(l[i-1][j])+m[i][j])
        l[i][j][2]=max(l[i][j-1][1]+m[i][j],l[i][j-1][2])
        l[i][j][3]=max(l[i][j-1][2]+m[i][j],l[i][j-1][3])
print(max(l[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline

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

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

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

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

    # print(f'{dp=}')
    ans = max(dp[-2][-2])
    print(ans)


if __name__ == '__main__':
    main()

# def binary_search(*, ok, ng, func):
#     while abs(ok - ng) > 1:
#         mid = (ok + ng) // 2
#         if func(mid):
#             ok = mid
#         else:
#             ng = mid
#     return ok

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
def main():
    r,c,k=map(int,input().split())
    a=[list(map(int,input().split())) for _ in range(k)]
    dp=[[[0,0,0,0,0]for _ in range(c+1)]for _ in range(r+1)]
    b=[[0 for _ in range(c+1)] for _ in range(r+1)]
    for x,y,z in a:
        b[x][y]=z
    for i in range(1,r+1):
        for j in range(1,c+1):
            v=b[i][j]
            if b==0:
                dp[i][j][0]=max(dp[i][j-1][0],dp[i-1][j][0],dp[i-1][j][1],dp[i-1][j][2],dp[i-1][j][3])
                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][0]=max(dp[i][j-1][0],dp[i-1][j][0],dp[i-1][j][1],dp[i-1][j][2],dp[i-1][j][3])
                dp[i][j][1]=max(dp[i][j-1][1],dp[i][j-1][0]+v,dp[i-1][j][0]+v,dp[i-1][j][1]+v,dp[i-1][j][2]+v,dp[i-1][j][3]+v)
                dp[i][j][2]=max(dp[i][j-1][2],dp[i][j-1][1]+v)
                dp[i][j][3]=max(dp[i][j-1][3],dp[i][j-1][2]+v)
    print(max(dp[i][j]))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
r,c,k=map(int,input().split())
v=[[0]*c for _ in range(r)]
for _ in range(k):
    ri,ci,a=map(int,input().split())
    ri-=1
    ci-=1
    v[ri][ci]=a
dp=[[[0]*4 for _ in range(c)] for i in range(r)]
#print(dp)
if v[0][0]>0:
    dp[0][0][1]=v[0][0]
for i in range(r):
    for j in range(c):
        if i>0:
            if v[i][j]>0:
                for k in range(min(3,j+1)+1):
                    dp[i][j][1]=max(dp[i][j][1],dp[i-1][j][k]+v[i][j])
            for k in range(4):
                dp[i][j][k]=max(dp[i][j][k],dp[i-1][j][k])
        if j>0:
            if v[i][j]>0:
                for k in range(min(3,j+1)+1):
                    if k>0:
                        dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k-1]+v[i][j])
            for k in range(4):
                dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k])
#print(dp)
print(max(dp[r-1][c-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque, defaultdict
#deque(l), pop(), append(x), popleft(), appendleft(x)
#q.rotate(n)で → にn回ローテート
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations,product#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
from functools import reduce,lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printe(*x):print("## ",*x,file=sys.stderr)
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def binr(x): return bin(x)[2:]
def bitcount(x): #xは64bit整数
    x= x - ((x >> 1) & 0x5555555555555555)
    x= (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x= (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f 
    x+= (x >> 8); x+= (x >> 16); x+= (x >> 32) 
    return x & 0x7f

def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reverse=True)  #二個目の要素で降順並び替え

    #N = int(input())
    R,C,K = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    base=5000
    S=[]
    for i in range(K):
        r,c,v = map(int, input().split())
        r-=1
        c-=1
        S.append((r*base+c,v))

    S.sort(key=itemgetter(0))

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

    p=0
    
    for i in range(R):
        dpi=dp[i]
        for j in range(C):
            cv=0
            
            if p<K and i*base+j==S[p][0]:
                cv=S[p][1]
                p+=1

            for k in range(4):
                if j>0:
                    dpi[j][k]=max(dpi[j-1][k],dpi[j][k])
                if i>0:
                    dpi[j][0]=max(dp[i-1][j][k],dpi[j][0])
            if cv!=0:
                for k in range(2,-1,-1):
                    dpi[j][k+1]=max(dpi[j][k]+cv,dpi[j][k+1])
                #printe(dp)
    print(max(dp[-1][-1]))



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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


r, c, k = map(int, input().split())
info = [list(map(int, input().split())) for i in range(k)]
INF = 10 ** 18

item = [[0] * c for i in range(r)]
for i, j, v in info:
    i -= 1
    j -= 1
    item[i][j] = v

dp = [[[-INF] * 4 for i in range(c + 1)] for i in range(r + 1)]
for i in range(r + 1):
    dp[i][0][0] = 0
for j in range(c + 1):
    dp[0][j][0] = 0
    
for i in range(r):
    for j in range(c):
        val = item[i][j]
        dp[i + 1][j + 1][0] = max(dp[i + 1][j][0], dp[i][j + 1][0], dp[i][j + 1][1], dp[i][j + 1][2], dp[i][j + 1][3])
        dp[i + 1][j + 1][1] = max(dp[i + 1][j][1], dp[i + 1][j][0] + val,  dp[i][j + 1][0] + val, dp[i][j + 1][1] + val, dp[i][j + 1][2] + val, dp[i][j + 1][3] + val)
        dp[i + 1][j + 1][2] = max(dp[i + 1][j][2], dp[i + 1][j][1] + val)
        dp[i + 1][j + 1][3] = max(dp[i + 1][j][3], dp[i + 1][j][2] + val)
                                   
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())

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

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

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

for i in range(R):
    for j in range(C):
        if i == 0:
            break
        if G[i][j] is not None:
            for k in range(4):
                if dp[i][j + 1][k] is not None:
                    dp[i + 1][j + 1][1] = max(dp[i + 1][j + 1][0], dp[i][j + 1][k]) + G[i][j]
                    dp[i + 1][j + 1][0] = max(dp[i + 1][j + 1][0], dp[i][j + 1][k])
        else:
            for k in range(4):
                if dp[i][j + 1][k] is not None:
                    dp[i + 1][j + 1][0] = max(dp[i + 1][j + 1][0], dp[i][j + 1][k])

    for j in range(C):
        if G[i][j] is not None:
            for k in range(3):
                if dp[i + 1][j + 1][k] is not None and dp[i + 1][j][k] is not None:
                    if dp[i + 1][j][k + 1] is not None:
                        if dp[i + 1][j + 1][k + 1] is not None:
                            dp[i + 1][j + 1][k + 1] = max(dp[i + 1][j + 1][k + 1], dp[i + 1][j][k] + G[i][j], dp[i + 1][j][k + 1])
                        else:
                            dp[i + 1][j + 1][k + 1] = max(dp[i + 1][j][k + 1], dp[i + 1][j][k] + G[i][j])
                    else:
                        if dp[i + 1][j + 1][k + 1] is not None:
                            dp[i + 1][j + 1][k + 1] = max(dp[i + 1][j + 1][k + 1], dp[i + 1][j][k] + G[i][j])
                        else:
                            dp[i + 1][j + 1][k + 1] = dp[i + 1][j][k] + G[i][j]
        else:
            for k in range(4):
                if dp[i + 1][j][k] is not None:
                    if dp[i + 1][j + 1][k] is not None:
                        dp[i + 1][j + 1][k] = max(dp[i + 1][j + 1][k], dp[i + 1][j][k])
                    else:
                        dp[i + 1][j + 1][k] = dp[i + 1][j][k]

res = 0
for d in dp[R][C]:
    if d is not None:
        res = max(res, d)

print(res)

Submission status: Time Limit Exceeded

Solution code:
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(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] = dp[i][j-1][k]
      #上から取らない
      dp[i][j][0] = max(dp[i][j][0],max(dp[i-1][j]))
      if item[i-1][j-1]>0:
        #上からとる
        dp[i][j][1] = max(dp[i][j][1],max(dp[i-1][j])+item[i-1][j-1])
        for k in range(1,4): #横から取る
          dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k-1]+item[i-1][j-1])
  ans = max(dp[-1][-1])
  return ans
print(solve())

Submission status: Time Limit Exceeded

Solution code:
from collections import *
r,c,k=map(int,input().split())
l=[(1,0),(0,1)]
v=[[0]*r for i in range(c)]
for i in range(k):
    R,C,V=map(int,input().split())
    R,C=R-1,C-1
    v[C][R]=V
q=deque()
q.append((0,0,0,0,0,0))
ans=0
while q:
    y,x,t,t1,t2,t3=q.popleft()
    if v[y][x]!=0:
        if t3<v[y][x]:
            t3=v[y][x]
    if x==r-1 and y==c-1:
        t+=t1+t2+t3
        if ans<t:
            ans=t
    for yy,xx in l:
        ny,nx=y+yy,x+xx
        if 0<=ny<c and 0<=nx<r:
            if xx==1:
                t+=t1+t2+t3
                t1,t2,t3=0,0,0
            else:
                if t3>t1:
                    t1,t2,t3=t3,t1,t2
                elif t3>t2:
                    t1,t2,t3=t1,t3,t2
            q.append((ny,nx,t,t1,t2,t3))
print(ans)

Submission status: Time Limit Exceeded

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

def main():
    R, C, K = map(int, input().split())
    State = [[0]*R for _ in range(C)]
    for _ in range(K):
        r, c, v = map(int, input().split())
        State[c-1][r-1] += v

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

    for r in range(R):
        for c in range(C):
            for n in range(4):
                if dp[(c+1)*(R+1)+r][n] > dp[(c+1)*(R+1)+r+1][0]:
                    dp[(c+1)*(R+1)+r+1][0] = dp[(c+1)*(R+1)+r][n]
                if dp[(c+1)*(R+1)+r][n] + State[c][r] > dp[(c+1)*(R+1)+r+1][1]:
                    dp[(c+1)*(R+1)+r+1][1] = dp[(c+1)*(R+1)+r][n] + State[c][r]
                if dp[c*(R+1)+r+1][n] > dp[(c+1)*(R+1)+r+1][n]:
                    dp[(c+1)*(R+1)+r+1][n] = dp[c*(R+1)+r+1][n]
                if n < 3 and dp[c*(R+1)+r+1][n] + State[c][r] > dp[(c+1)*(R+1)+r+1][n+1]:
                    dp[(c+1)*(R+1)+r+1][n+1] = dp[c*(R+1)+r+1][n] + State[c][r]
        
    print(max(dp[C*(R+1)+R]))

if __name__ == "__main__":
    main()