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())
    item_map = [[0]*C for _ in range(R)]

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

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

Submission status: Time Limit Exceeded

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

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

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

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

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

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

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

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/abc175/submissions/15965930

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

    H, W, K = map(int, input().split())

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

    dp0 = [0] * (W + 1)
    dp1 = [0] * (W + 1)
    dp2 = [0] * (W + 1)
    dp3 = [0] * (W + 1)
    # dpx:=行内取得x個以下の最大値
    # <cは更新済の同じ行の値
    # c<=は前の行の値

    for r in range(H):
        for c in range(W):
            v = G[r][c]

            dp0[c] = max(dp0[c], dp3[c])  # 垂直移動
            vertical_take = dp0[c] + v  # 垂直移動+(r,c)取得

            dp3[c] = max(dp3[c - 1], dp2[c - 1] + v, vertical_take)
            dp2[c] = max(dp2[c - 1], dp1[c - 1] + v, vertical_take)
            dp1[c] = max(dp1[c - 1], dp0[c - 1] + v, vertical_take)
            # 水平移動（左）から来て取らない
            # 水平移動（左）から来て取る
            # 垂直移動で来て取らない:=dp0
            # 垂直移動で来て取る:=dpx(x>0)

            # print(f'{dp0=}')
            # print(f'{dp1=}')
            # print(f'{dp2=}')
            # print(f'{dp3=}')
            # print('*******************')

    print(dp3[-2])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

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

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

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

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

Submission status: Time Limit Exceeded

Solution code:
r,c,k=map(int,input().split())
T=[[] for i in range(3001)]

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

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

for i in range(1,r+1):
    head=0
    T[i].sort()
    for q in range(1,c+1):
        if len(T[i])>head and T[i][head][0]==q:
            pri= T[i][head][1]
            head+=1
        else:
            pri=0
        dp[i][q][0]=max(max(dp[i-1][q]),dp[i][q-1][0])
        dp[i][q][1]=dp[i][q][0]+pri
        dp[i][q][3]=max(dp[i][q-1][3],dp[i][q-1][2]+pri)
        dp[i][q][2]=max(dp[i][q-1][2],dp[i][q-1][1]+pri)
        dp[i][q][1]=max(dp[i][q-1][1],dp[i][q-1][0]+pri,dp[i][q][1])

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

Submission status: Time Limit Exceeded

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

fuck=[list(map(int,input().split())) for _ in range(k)]

rck=[[0]*c for _ in range(r)]

for [rr,cc,kk] in fuck:
    rck[rr-1][cc-1]=kk

#dp[y][x][cnt]

dp=[[[0]*4 for _ in range(c)] for _ in range(r)]
#print(dp)
for y in range(r):
    for x in range(c):
        #1行目
        if y == 0:
            if x==0:
                dp[y][x][1]=rck[y][x]
            if x>=1:
                dp[y][x][1]=max(dp[y][x-1][1],rck[y][x])
                dp[y][x][2]=max(dp[y][x-1][2],dp[y][x-1][1]+rck[y][x])
            if x>=2:
                dp[y][x][3]=max(dp[y][x-1][3],dp[y][x-1][2]+rck[y][x])
        else:
            #1は、上0+1 or 左0+1 or 上1 or 左1
            #count1ケース
            for i in range(1,4):
                if i==1:
                    uemax=max([max(dp[y-1][x][1],dp[y-1][x][2],dp[y-1][x][3])])
                    dp[y][x][i]=uemax+rck[y][x]
                    if x>0:
                        dp[y][x][i]=max(dp[y][x][i],dp[y][x-1][i])
                elif i>=2:
                    if x>=1:
                        dp[y][x][i]=max(dp[y][x-1][i],dp[y][x-1][i-1]+rck[y][x])

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

Submission status: Time Limit Exceeded

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

R, C, K = map(int,input().split())
RC = [[0] * (C+1) for _ in range(R+1)]

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


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

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

Submission status: Time Limit Exceeded

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]

    R,C,K = LI()

    m = [[0] * (C+1) for _ in range(R+1)]
    dp = [[[0] * 4 for _ in range(C+1)] for _ in range(R+1)]
    for _ in range(K):
        r,c,v = LI()
        m[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-1][0],max(dp[i-1][j]))
            if m[i][j] > 0:
                for k in range(1,4):
                    dp[i][j][k] = max(dp[i][j-1][k],dp[i][j-1][k-1]+m[i][j])
                dp[i][j][1] = max(dp[i][j][1],max(dp[i-1][j])+m[i][j])
            else:
                for k in range(1,4):
                    dp[i][j][k] = dp[i][j-1][k]
    print(max(dp[-1][-1]))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

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

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

for ir in range(R):
    for ic in range(C):
        for k in range(2,-1,-1):
            #-拾う拾わない遷移-#
            dp[ir][ic][k+1] = max(dp[ir][ic][k+1],dp[ir][ic][k]+itemMap[ir][ic])
        #-位置遷移-#
        for k in range(4):
            dp[ir+1][ic][0] = max(dp[ir+1][ic][0],dp[ir][ic][k])
            dp[ir][ic+1][k] = max(dp [ir][ic+1][k],dp[ir][ic][k])

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

Submission status: Time Limit Exceeded

Solution code:
from math import *
import fractions
import collections
import itertools
import pprint
from collections import deque
from heapq import *
R,C,K=map(int,input().split())
table=[[-float("inf") for _ in range(C)] for _ in range(R)]
dp=[[[-float("inf") for _ in range(4)] for _ in range(C)] for _ in range(R)]
for i in range(K):
    r,c,v=map(int,input().split())
    table[r-1][c-1]=v
#print(table)
d=deque()
dp[0][0][0]=0
if table[0][0]!=-float("inf"):
    dp[0][0][1]=table[0][0]
d.append([0,0])
tosee=[[0 for _ in range(C)] for _ in range(R)]
tosee[0][0]=1
while len(d)>0:
    r,c=d.popleft()
    flag=0
    tosee[r][c]=0
    if r<R-1:
        for i in range(4):
            if dp[r][c][i]>dp[r+1][c][0]:
                dp[r+1][c][0]=dp[r][c][i]
                flag=1
        if table[r+1][c]!=-float("inf"):
            for i in range(4):
                if dp[r][c][i]+table[r+1][c] > dp[r + 1][c][1]:
                    dp[r + 1][c][1] = dp[r][c][i]+table[r+1][c]
                    flag = 1
        if (flag==1)and(tosee[r+1][c]==0):
            d.append([r+1,c])
            tosee[r+1][c]=1
            flag=0
    if c<C-1:
        for i in range(4):
            if dp[r][c][i]>dp[r][c+1][i]:
                dp[r][c+1][i]=dp[r][c][i]
                flag=1
        if table[r][c+1]!=-float("inf"):
            for i in range(3):
                if dp[r][c][i]+table[r][c+1]>dp[r][c+1][i+1]:
                    dp[r][c+1][i+1]=dp[r][c][i]+table[r][c+1]
                    flag=1
        if (flag==1)and(tosee[r][c+1]==0):
            d.append([r,c+1])
            tosee[r][c+1] = 1
            flag=0
    #print(dp,d)
print(max(dp[R-1][C-1]))

Submission status: Time Limit Exceeded

Solution code:
from math import *
import fractions
import collections
import itertools
import pprint
from collections import deque
from heapq import *
R,C,K=map(int,input().split())
table=[[-float("inf") for _ in range(C)] for _ in range(R)]
dp=[[[-float("inf") for _ in range(4)] for _ in range(C)] for _ in range(R)]
for i in range(K):
    r,c,v=map(int,input().split())
    table[r-1][c-1]=v
#print(table)
d=deque()
dp[0][0][0]=0
if table[0][0]!=-float("inf"):
    dp[0][0][1]=table[0][0]
d.append([0,0])
while len(d)>0:
    r,c=d.popleft()
    flag=0
    if r<R-1:
        for i in range(4):
            if dp[r][c][i]>dp[r+1][c][0]:
                dp[r+1][c][0]=dp[r][c][i]
                flag=1
        if table[r+1][c]!=-float("inf"):
            for i in range(4):
                if dp[r][c][i]+table[r+1][c] > dp[r + 1][c][1]:
                    dp[r + 1][c][1] = dp[r][c][i]+table[r+1][c]
                    flag = 1
        if flag==1:
            d.append([r+1,c])
            flag=0
    if c<C-1:
        for i in range(4):
            if dp[r][c][i]>dp[r][c+1][i]:
                dp[r][c+1][i]=dp[r][c][i]
                flag=1
        if table[r][c+1]!=-float("inf"):
            for i in range(3):
                if dp[r][c][i]+table[r][c+1]>dp[r][c+1][i+1]:
                    dp[r][c+1][i+1]=dp[r][c][i]+table[r][c+1]
                    flag=1
        if flag==1:
            d.append([r,c+1])
            flag=0
    #print(dp,d)
print(max(dp[R-1][C-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys,math,collections,itertools
input = sys.stdin.readline

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

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

for ir in range(R):
    for ic in range(C):
        for k in range(2,-1,-1):
            #-拾う拾わない遷移-#
            dp[ir][ic][k+1] = max(dp[ir][ic][k+1],dp[ir][ic][k]+itemMap[ir][ic])
        #-位置遷移-#
        for k in range(4):
            dp[ir+1][ic][0] = max(dp[ir+1][ic][0],dp[ir][ic][k])
            dp[ir][ic+1][k] = max(dp [ir][ic+1][k],dp[ir][ic][k])

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

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 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])
			
			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]=copy.deepcopy(sts[iii-1])
						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:
R, C, K = map(int, input().split())
dp = [[[0] * 4 for _ in range(C + 1)]for _ in range(R + 1)]
grid = [[0] * C for _ in range(R)]
for _ in range(K):
    r, c, v = map(int, input().split())
    grid[r - 1][c - 1] = v
for i in range(R):
    for j in range(C):
        for k in range(2, -1, -1):
            # chmax(dp[i][j][k + 1], dp[i][j][k] + grid[i][j])
            dp[i][j][k + 1] = max(dp[i][j][k + 1], dp[i][j][k] + grid[i][j])
        for k in range(4):
            dp[i + 1][j][0] = max(dp[i + 1][j][0], dp[i][j][k])
            dp[i][j + 1][k] = max(dp[i][j + 1][k], dp[i][j][k])
ans = 0
for k in range(4):
    ans = max(ans, dp[R - 1][C - 1][k])
print(ans)

Submission status: Time Limit Exceeded

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

    H, W, K = map(int, input().split())

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

    dp = [[[0] * 4 for _ in range(W + 1)] for _ in range(H + 1)]
    for r in range(H):
        for c in range(W):
            cell = dp[r][c]
            up = dp[r - 1][c]
            left = dp[r][c - 1]

            for k in range(4):
                cell[0] = max(cell[0], up[k])
                cell[k] = max(cell[k], left[k])

            for k in range(2, -1, -1):
                cell[k + 1] = max(
                    cell[k + 1],
                    cell[k] + G[r][c])

    # for k in range(4):
    #     for row in range(H):
    #         for col in range(W):
    #             print(dp[row][col][k], end=' ')
    #         print()
    #     print()

    # print(*G, sep='\n')

    ans = max(dp[-2][-2])
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
r,c,k=[int(i) for i in raw_input().split()]
a=[[-1 for i in xrange(3005)]for j in xrange(3005)]
for i in range(k):
    x,y,z=[int(j) for j in raw_input().split()]
    a[x-1][y-1]=z
dp=[[[0,0,0,0] for i in xrange(3005)]for j in xrange(3005)]
for i in range(r+1):
    for j in range(c+1):
        if(i>0):
            dp[i][j][0]=dp[i-1][j][3]
            dp[i][j][1]=dp[i-1][j][3]
            dp[i][j][2]=dp[i-1][j][3]
            dp[i][j][3]=dp[i-1][j][3]
        if j>0:
            dp[i][j][3]=max(dp[i][j][3],dp[i][j-1][3])
            dp[i][j][2]=max(dp[i][j][2],dp[i][j-1][2])
            dp[i][j][1]=max(dp[i][j][1],dp[i][j-1][1])
            dp[i][j][0]=max(dp[i][j][0],dp[i][j-1][0])
        if(i>0 and j>0 and a[i-1][j-1]!=-1):
            dp[i][j][3]=max(dp[i][j][2]+a[i-1][j-1],dp[i][j-1][3])
            dp[i][j][2]=max(dp[i][j][1]+a[i-1][j-1],dp[i][j-1][2])
            dp[i][j][1]=max(dp[i][j][0]+a[i-1][j-1],dp[i][j-1][1])
        
print max(dp[r][c])

Submission status: Time Limit Exceeded

Solution code:
r,c,k=[int(i) for i in input().split()]
a=[[-1 for i in range(c)]for j in range(r)]
for i in range(k):
    x,y,z=[int(j) for j in input().split()]
    a[x-1][y-1]=z
dp=[[[0,0,0,0] for i in range(c+1)]for j in range(r+1)]
for i in range(r+1):
    for j in range(c+1):
        if(i>0):
            dp[i][j][0]=dp[i-1][j][3]
            dp[i][j][1]=dp[i-1][j][3]
            dp[i][j][2]=dp[i-1][j][3]
            dp[i][j][3]=dp[i-1][j][3]
        if j>0:
            dp[i][j][3]=max(dp[i][j][3],dp[i][j-1][3])
            dp[i][j][2]=max(dp[i][j][2],dp[i][j-1][2])
            dp[i][j][1]=max(dp[i][j][1],dp[i][j-1][1])
            dp[i][j][0]=max(dp[i][j][0],dp[i][j-1][0])
        if(i>0 and j>0 and a[i-1][j-1]!=-1):
            dp[i][j][3]=max(dp[i][j][2]+a[i-1][j-1],dp[i][j-1][3])
            dp[i][j][2]=max(dp[i][j][1]+a[i-1][j-1],dp[i][j-1][2])
            dp[i][j][1]=max(dp[i][j][0]+a[i-1][j-1],dp[i][j-1][1])
        
print(max(dp[r][c]))

Submission status: Time Limit Exceeded

Solution code:
r,c,k=[int(i) for i in input().split()]
a=[[-1 for i in range(c)]for j in range(r)]
for i in range(k):
    x,y,z=[int(j) for j in input().split()]
    a[x-1][y-1]=z
dp=[[[0,0,0,0] for i in range(c+1)]for j in range(r+1)]
for i in range(r+1):
    for j in range(c+1):
        if(i>0):
            dp[i][j][0]=dp[i-1][j][3]
            dp[i][j][1]=dp[i-1][j][3]
            dp[i][j][2]=dp[i-1][j][3]
            dp[i][j][3]=dp[i-1][j][3]
        if j>0:
            dp[i][j][3]=max(dp[i][j][3],dp[i][j-1][3])
            dp[i][j][2]=max(dp[i][j][2],dp[i][j-1][2])
            dp[i][j][1]=max(dp[i][j][1],dp[i][j-1][1])
            dp[i][j][0]=max(dp[i][j][0],dp[i][j-1][0])
        if(i>0 and j>0 and a[i-1][j-1]!=-1):
            dp[i][j][3]=max(dp[i][j][2]+a[i-1][j-1],dp[i][j-1][3])
            dp[i][j][2]=max(dp[i][j][1]+a[i-1][j-1],dp[i][j-1][2])
            dp[i][j][1]=max(dp[i][j][0]+a[i-1][j-1],dp[i][j-1][1])
        
print(max(dp[r][c]))

Submission status: Time Limit Exceeded

Solution code:
R, C, K = list(map(int,input().split()))
v = [[0 for _ in range(C + 1)] for _ in range(R + 1)]
for i in range(K):  
    in1, in2, in3 = list(map(int,input().split()))
    v[in1][in2] = in3

dp = [[[0 for _ in range(4)] for _ in range(C + 1)] for _ in range(R + 1)]
    
for i in range(R):
    for j in range(C):
        dp[i + 1][j + 1][0] = max(dp[i][j + 1][3], dp[i + 1][j][0])
        for k in range(3):
            dp[i + 1][j + 1][k + 1] = max(dp[i][j + 1][3] + v[i + 1][j + 1], max(dp[i + 1][j][k] + v[i + 1][j + 1], dp[i + 1][j][k + 1]))
            
ans = dp[R][C][3]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7

from types import GeneratorType

def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to

    return wrappedfunc

@bootstrap
def recur(row,col):
    if dp[row][col]:
        yield dp[row][col]
        return
    l=[]
    if row==r:
        l=sorted(mat[row][col:],reverse=True)
        dp[row][col]=sum(l[:3])
    else:
        for i in range(col,c+1):
            l.append(mat[row][i])
            l.sort(reverse=True)
            dp[row][col]=max(dp[row][col],sum(l[:3])+(yield recur(row+1,i)))
    yield dp[row][col]

r,c,k=mdata()
mat=[[0 for i in range(c+1)] for j in range(r+1)]
for i in range(k):
    ri,ci,vi=mdata()
    mat[ri][ci]=vi
dp=[[0 for i in range(c+1)] for j in range(r+1)]
out(recur(1,1))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import sys

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

v = np.zeros((r,c),dtype=np.int64)

readline = sys.stdin.readline

for i in range(k):
    x,y,z = map(int, readline().split())
    x -= 1
    y -= 1
    v[x][y] = z

dp = np.zeros((r+1,c+1,4),dtype=np.int64)

listC = list(range(c))

for i in range(r):
    dp1 = dp[i]
    dp2 = dp[i + 1]
    for j in listC:
        dp2[j + 1][0] = dp2[j][0]
        for s in range(1,4):
            dp2[j + 1][0] = max(dp2[j + 1][0],dp1[j + 1][s])
        for s in range(4):
            dp2[j + 1][1] = max([dp2[j + 1][1],dp2[j][1],dp1[j + 1][s] + v[i][j]])
        for s in range(2,4):
            dp2[j + 1][s] = max([dp2[j + 1][s],dp2[j][s],dp2[j][s-1] + v[i][j]])

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

v = np.zeros((r,c),dtype=np.int64)

for i in range(k):
    x,y,z = map(int, input().split())
    x -= 1
    y -= 1
    v[x][y] = z

dp = np.zeros((r+1,c+1,4),dtype=np.int64)

listC = list(range(c))

for i in range(r):
    dp1 = dp[i]
    dp2 = dp[i + 1]
    for j in listC:
        dp2[j + 1][0] = dp2[j][0]
        for s in range(1,4):
            dp2[j + 1][0] = max(dp2[j + 1][0],dp1[j + 1][s])
        for s in range(4):
            dp2[j + 1][1] = max([dp2[j + 1][1],dp2[j][1],dp1[j + 1][s] + v[i][j]])
        for s in range(2,4):
            dp2[j + 1][s] = max([dp2[j + 1][s],dp2[j][s],dp2[j][s-1] + v[i][j]])

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
import collections
import bisect
import itertools

# import numpy as np

sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))


# ===CODE===

def main():
    r, c, k = ns()

    mat = [[0] * (c + 1) for __ in range(r + 1)]
    for _ in range(k):
        x, y, v = ns()
        x, y = x - 1, y - 1
        mat[x][y] = v

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

    for i in range(r):
        for j in range(c):
            for n in range(2, -1, -1):
                dp[i][j][n + 1] = max(dp[i][j][n + 1], dp[i][j][n] + mat[i][j])

            dp[i + 1][j][0] = max(dp[i][j])
            for n in range(4):
                dp[i][j + 1][n] = max(dp[i][j + 1][n], dp[i][j][n])

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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
R,C,K=map(int,input().split())
Item=[["*"]*(C+1)]+[["*"]+[0]*C for _ in range(R)]
T=3

for _ in range(K):
    y,x,v=map(int,input().split())
    Item[y][x]=v

DP=[[[0]*(T+1) for _ in range(C+1)] for _ in range(R+1)]

for y in range(1,R+1):
    for x in range(1,C+1):
        #右に移動
        for k in range(1,T+1):
            DP[y][x][k]=max(DP[y][x][k],DP[y][x-1][k],DP[y][x-1][k-1]+Item[y][x])

        #下に移動
        if y<R:
            for k in range(T+1):
                DP[y+1][x][0]=DP[y][x][-1]
                DP[y+1][x][1]=DP[y+1][x][2]=DP[y+1][x][3]=DP[y+1][x][0]+Item[y+1][x]

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