Problem:


Score : 500 points

Problem Statement

There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i.

Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square).

He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.

Find the maximum possible sum of the values of items he picks up.

Constraints

1 \leq R, C \leq 3000

1 \leq K \leq \min(2 \times 10^5, R \times C)

1 \leq r_i \leq R

1 \leq c_i \leq C

(r_i, c_i) \neq (r_j, c_j) (i \neq j)

1 \leq v_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R C K
r_1 c_1 v_1
r_2 c_2 v_2
:
r_K c_K v_K

Output

Print the maximum possible sum of the values of items Takahashi picks up.

Sample Input 1

2 2 3
1 1 3
2 1 4
1 2 5

Sample Output 1

8

He has two ways to get to the goal:

Visit (1, 1), (1, 2), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 5 = 8.

Visit (1, 1), (2, 1), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 4 = 7.

Thus, the maximum possible sum of the values of items he picks up is 8.

Sample Input 2

2 5 5
1 1 3
2 4 20
1 2 1
1 3 4
1 4 2

Sample Output 2

29

We have four items in the 1-st row. The optimal choices are as follows:

Visit (1, 1) (1, 2), (1, 3), (1, 4), (2, 4), and (2, 5), in this order, and pick up all items except the one on (1, 2). Then, the total value of the items he picks up will be 3 + 4 + 2 + 20 = 29.

Sample Input 3

4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10

Sample Output 3

142



Sample input:
2 2 3
1 1 3
2 1 4
1 2 5


Sample output:
8

Submission status: Time Limit Exceeded

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

I = [[0 for j in range(C)] for i in range(R)]
for _ in range(K):
    r, c, v = map(int, input().split())
    I[r-1][c-1] = v   # 0-indexed

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


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

ans = 0
for k in range(4):
    if k <= 2:
        ans = max(ans, dp[R-1][C-1][k]+I[R-1][C-1])
    else:
        ans = max(ans, dp[R-1][C-1][k])
print(ans)

Submission status: Time Limit Exceeded

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

I = [[0 for j in range(C)] for i in range(R)]
for _ in range(K):
    r, c, v = map(int, input().split())
    I[r-1][c-1] = v   # 0-indexed

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


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

ans = 0
for k in range(4):
    if k <= 2:
        ans = max(ans, dp[R-1][C-1][k]+I[R-1][C-1])
    else:
        ans = max(ans, dp[R-1][C-1][k])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
R, C, K = map(int, input().split())

I = defaultdict(int)
for _ in range(K):
    r, c, v = map(int, input().split())
    I[(r-1, c-1)] = v   # 0-indexed

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


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

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

Submission status: Time Limit Exceeded

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

I = [[0 for j in range(C)] for i in range(R)]
for _ in range(K):
    r, c, v = map(int, input().split())
    I[r-1][c-1] = v   # 0-indexed

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


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

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

Submission status: Time Limit Exceeded

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

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


show_flg=False
show_flg=True

ans=0

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

class multi_dim_list:
    def __init__(self,dim,*a):
        self.length=1
        self.size=[1]
        for i in a[::-1]:
            self.length*=i
            self.size+=self.length,
        self.size=self.size[-2:0:-1]+[1]
        self.arr=[0]*self.length
    
    def __getitem__(self,indice):
        idx=0
        for i,s in zip(indice,self.size):
            idx+=i*s
        return self.arr[idx]

    def __setitem__(self,indice,value):
        idx=0
        for i,s in zip(indice,self.size):
            idx+=i*s
        self.arr[idx]=value

'''
I,J,K=3,5,4
dd=multi_dim_list(3,I,J,K)
c=0
for i in range(I):
    for j in range(J):
        for k in range(K):
            dd.arr[i*J*K+j*K+k]=c
            c+=1
'''
#dp=[[[0]*4 for i in range(w+1)] for i in range(h+1)]
dp=multi_dim_list(3,h+1,w+1,4)

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

#ans=max(dp[h][w])
ans=max(dp.arr[h*(w+1)*4+w*4:])
print(ans)

Submission status: Time Limit Exceeded

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

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

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

n = [0] * (C + 1)
for i in range(R):
    c = [0] * 4
    c[0] = n[0]
    for j in range(C):
        if goods[i][j] != 0:
            for k in range(2, -1, -1):
                if c[k] + goods[i][j] > c[k + 1]:
                    c[k + 1] = c[k] + goods[i][j]
        for k in range(4):
            if c[k] > n[j]:
                n[j] = c[k]
        if n[j + 1] > c[0]:
            c[0] = n[j + 1]

print(max(c))

Submission status: Time Limit Exceeded

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

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

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

dp = [[[0] * 4 for _ in range(C + 1)] for _ in range(R + 1)]
for i in range(R):
    for j in range(C):
        if goods[i][j] != 0:
            for k in range(2, -1, -1):
                if dp[i][j][k] + goods[i][j] > dp[i][j][k + 1]:
                    dp[i][j][k + 1] = dp[i][j][k] + goods[i][j]
        for k in range(4):
            if dp[i][j][k] > dp[i][j + 1][k]:
                dp[i][j + 1][k] = dp[i][j][k]
            if dp[i][j][k] > dp[i + 1][j][0]:
                dp[i + 1][j][0] = dp[i][j][k]

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

Submission status: Time Limit Exceeded

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

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

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

dp = [[[0] * 4 for _ in range(C + 1)] for _ in range(R + 1)]
for i in range(R):
    for j in range(C):
        if goods[i][j] != 0:
            for k in range(2, -1, -1):
                dp[i][j][k + 1] = max(dp[i][j][k + 1], dp[i][j][k] + goods[i][j])
        for k in range(4):
            dp[i][j + 1][k] = max(dp[i][j + 1][k], dp[i][j][k])
            dp[i + 1][j][0] = max(dp[i + 1][j][0], dp[i][j][k])

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

Submission status: Time Limit Exceeded

Solution code:
"""
dp[i][j]　=> i行目j列目がゴールの場合の最大値
"""
def main():
    import sys
    input = sys.stdin.readline
    R,C,K = map(int,input().split())
    items = [[0]*(C) for _ in range(R)]

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

    dp = [[[0]*4 for _ in range(C)] for _ in range(R)]
    dp[0][0][1] = items[0][0]
    for i in range(R):
        for j in range(C):
            v = items[i][j]
            if i==0 and j == 0:
                continue

            if i!=0:
                #上から入る場合のシミュレート
                dp[i][j][0] = max(dp[i][j][0],max(dp[i-1][j]))
                if v:
                    dp[i][j][1] = max(dp[i][j][1],max(dp[i-1][j])+v)

            if j!=0:
                #左から入る場合のシミュレート
                dp[i][j][0] = max(dp[i][j][0],dp[i][j-1][0])
                if v:
                    #itemが存在する場合の処理
                    for k in range(1,4):
                        dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k-1]+v,dp[i][j-1][k])
                else:
                    for k in range(1,4):
                        dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k])
    print(max(dp[-1][-1]))
main()

Submission status: Time Limit Exceeded

Solution code:
"""
dp[i][j]　=> i行目j列目がゴールの場合の最大値
"""

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

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

dp = [[[0]*4 for _ in range(C)] for _ in range(R)]
dp[0][0][1] = items[0][0]
for i in range(R):
    for j in range(C):
        v = items[i][j]
        if i==0 and j == 0:
            continue

        if i!=0:
            #上から入る場合のシミュレート
            dp[i][j][0] = max(dp[i][j][0],max(dp[i-1][j]))
            if v:
                dp[i][j][1] = max(dp[i][j][1],max(dp[i-1][j])+v)

        if j!=0:
            #左から入る場合のシミュレート
            dp[i][j][0] = max(dp[i][j][0],dp[i][j-1][0])
            if v:
                #itemが存在する場合の処理
                for k in range(1,4):
                    dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k-1]+v,dp[i][j-1][k])
            else:
                for k in range(1,4):
                    dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k])
print(max(dp[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import defaultdict
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

#sys.setrecursionlimit(10**8)

R,C,K=map(int,readline().split())
m = map(int, read().split())
I = zip(m, m, m) 

items = defaultdict(int)
for r,c,v in I:
  items[(r-1,c-1)] = v

dp = np.zeros([R,C,4],dtype=int)

for i in range(R):
  for j in range(C):
    if i == 0 and j > 0:
      dp[i,j,:] = dp[i,j-1,:]
    elif j == 0 and i > 0:
      dp[i,j,:] = dp[i-1,j,:].max() #reset
    elif i > 0 and j > 0:
      dp[i,j,:] = np.maximum(dp[i,j-1,:],dp[i-1,j,:].max()) #reset
    if items[(i,j)]:
      dp[i,j,1:] = np.maximum(dp[i,j,1:],dp[i,j,:-1]+items[(i,j)])

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

Submission status: Time Limit Exceeded

Solution code:
H,W,k = map(int, input().split())
# アイテムが何処に何個あるか
fs = [[0]*(W+1) for i in range(H+1)]
for i in range(k):
    h, w, v = map(int, input().split())
    h -= 1
    w -= 1
    fs[h][w] = v

mvs = [(0,1),(1,0)]
dp = [[[-1<<50 for i in range(W+1)] for j in range(H+1)] for k in range(4)]
# dp[n][i][j] n個取ったときの、i,jにおけるアイテム価値の最大値
from collections import deque
q = deque([])
q.append((0,0))
dp[0][0][0] = 0
dp[1][0][0] = fs[0][0]
for h in range(H):
    for w in range(W):
        dp[0][h][w+1] = max(dp[0][h][w+1], dp[0][h][w])
        dp[1][h][w+1] = max(dp[1][h][w+1], dp[1][h][w], dp[0][h][w] + fs[h][w+1])
        dp[2][h][w+1] = max(dp[2][h][w+1], dp[2][h][w], dp[1][h][w] + fs[h][w+1])
        dp[3][h][w+1] = max(dp[3][h][w+1], dp[3][h][w], dp[2][h][w] + fs[h][w+1])
    for w in range(W):
        mx = 0
        for i in range(4):
            # print("fe",i,h,w,"dp",dp[i][h][w])
            mx = max(mx,dp[i][h][w])
        dp[0][h+1][w] = mx
        dp[1][h+1][w] = mx + fs[h+1][w]

H -= 1
W -= 1
ans0 = dp[0][H][W]
ans1 = dp[1][H][W]
ans2 = dp[2][H][W]
ans3 = dp[3][H][W]
# print(fs)
# for i in range(3):
#     d = dp[i]
#     for r in d:
#         print(*r)
#     print("----------")
print(max(ans1,ans2,ans3))

Submission status: Time Limit Exceeded

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

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

A = {}
for _ in range(K):
  r,c,v = map(int, input().split())
  r,c = r-1, c-1
  A[(r,c)] = v
  
# dp[i][j][k] (i,j) まで見てかつ同じ行でk個まで見た時の最大価値
dp = [[[0] * 4 for _ in range(C)] for _ in range(R)]

for i in range(R):
  for j in range(C):
    if i > 0:
      dp[i][j][0] = max(dp[i][j][0], max(dp[i-1][j][0:4]))
    if j > 0:
      for k in range(4):
        dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k])
    if (i,j) in A:
      #print(i,j)
      v = A[(i,j)]
      for k in range(3,0,-1):
        dp[i][j][k] = max(dp[i][j][k], dp[i][j][k-1] + v)
      
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())

A = {}
for _ in range(K):
  r,c,v = map(int, input().split())
  r,c = r-1, c-1
  A[(r,c)] = v
  
# dp[i][j][k] (i,j) まで見てかつ同じ行でk個まで見た時の最大価値
dp = [[[0] * 4 for _ in range(C)] for _ in range(R)]

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

Submission status: Time Limit Exceeded

Solution code:
h,w,k=map(int,input().split())
dp=[[[0]*4 for _ in range(w+2)] for _ in range(h+2)]
f=[[0]*(w+1) for _ in range(h+1)]
for i in range(1,k+1):
  r,c,v=map(int,input().split())
  f[r][c]=v
for i in range(1,h+1):
  for j in range(1,w+1):
    for k in range(3,-1,-1):
      if k:dp[i][j][k]=max(dp[i][j][k],dp[i][j][k-1]+f[i][j])
      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])
print(max(dp[h][w]))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import defaultdict

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

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

dp = np.zeros([R,C,4],dtype=int)

for i in range(R):
  for j in range(C):
    if i == 0 and j > 0:
      dp[i,j,:] = dp[i,j-1,:]
    elif j == 0 and i > 0:
      dp[i,j,:] = dp[i-1,j,:].max() #reset
    elif i > 0 and j > 0:
      dp[i,j,:] = np.maximum(dp[i,j-1,:],dp[i-1,j,:].max()) #reset
    if items[(i,j)]:
      dp[i,j,1:] = np.maximum(dp[i,j,1:],dp[i,j,:-1]+items[(i,j)])

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import defaultdict

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

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

dp = np.zeros([R,C,4],dtype=int)

for i in range(R):
  for j in range(C):
    if i == 0 and j > 0:
      dp[i,j,:] = dp[i,j-1,:]
    elif j == 0 and i > 0:
      dp[i,j,:] = dp[i-1,j,:].max() #reset
    elif i > 0 and j > 0:
      dp[i,j,:] = np.maximum(dp[i,j-1,:],dp[i-1,j,:].max()) #reset
    dp[i,j,1:] = np.maximum(dp[i,j,1:],dp[i,j,:-1]+items[(i,j)])

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import defaultdict

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

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

dp = np.zeros([R,C,4],dtype=int)

for i in range(R):
  for j in range(C):
    if i == 0 and j > 0:
      dp[i,j,:] = dp[i,j-1,:]
    elif j == 0 and i > 0:
      dp[i,j,:] = dp[i-1,j,:].max() #reset
    elif i > 0 and j > 0:
      dp[i,j,:] = np.maximum(dp[i,j-1,:],dp[i-1,j,:].max()) #reset
    if items[(i,j)]: #decide picking an item or not
      dp[i,j,1:] = np.maximum(dp[i,j,1:],dp[i,j,:-1]+items[(i,j)])

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

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
# AOTコンパイルテスト
import sys
import numpy as np
from collections import defaultdict
def input(): return sys.stdin.readline().rstrip()

def solve(dp,item):
    dptmp1 = np.copy(dp)
    dptmp2 = np.copy(dp)
    dptmp3 = np.copy(dp)
    for i in range(len(item)):
        dptmp3[item[i][0]:] = np.fmax(dptmp3[item[i][0]:], dptmp2[item[i][0]]+item[i][1])
        dptmp2[item[i][0]:] = np.fmax(dptmp2[item[i][0]:], dptmp1[item[i][0]]+item[i][1])
        dptmp1[item[i][0]:] = np.fmax(dptmp1[item[i][0]:], dp[item[i][0]]+item[i][1])
    return dptmp3


if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC
 
    cc = CC('my_module')
    cc.export('solve', 'i8[:](i8[:],i8[:,:])')(solve)
    cc.compile()
    exit()

def main():
    R, C, K = map(int, input().split())
    items = defaultdict(list)
    for _ in range(K):
        r, c, v = map(int, input().split())
        items[r-1].append([c-1, v])
    dp = np.zeros(C, dtype=int)
    for RR in range(R):
        if items[RR]==[]:
          continue
        items[RR].sort(key=lambda x: x[0])
        dp=solve(dp,np.array(items[RR],dtype=int))
    print(dp[-1])

main()

Submission status: Time Limit Exceeded

Solution code:
# AOTコンパイルテスト
import sys
import numpy as np
from collections import defaultdict
def input(): return sys.stdin.readline().rstrip()

def solve(dp,item):
    dptmp1 = np.copy(dp)
    dptmp2 = np.copy(dp)
    dptmp3 = np.copy(dp)
    for i in range(len(item)):
        dptmp3[item[i][0]:] = np.fmax(dptmp3[item[i][0]:], dptmp2[item[i][0]]+item[i][1])
        dptmp2[item[i][0]:] = np.fmax(dptmp2[item[i][0]:], dptmp1[item[i][0]]+item[i][1])
        dptmp1[item[i][0]:] = np.fmax(dptmp1[item[i][0]:], dp[item[i][0]]+item[i][1])
    return dptmp3


if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC
 
    cc = CC('my_module')
    cc.export('solve', '(i8[:],i8[:,:])')(solve)
    cc.compile()
    exit()

R, C, K = map(int, input().split())
items = defaultdict(list)
for _ in range(K):
    r, c, v = map(int, input().split())
    items[r-1].append([c-1, v])
dp = np.zeros(C, dtype='int64')
for RR in range(R):
    if items[RR]==[]:
        continue
    items[RR].sort(key=lambda x: x[0])
    dp=solve(dp,np.array(items[RR],dtype='int64'))
print(dp[-1])

Submission status: Time Limit Exceeded

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

num = 4

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

val = [[0 for i in range(c+1)] for j in range(r+1)]

for i in range(K):
    r1,c1,v1 = map(int,input().split())
    val[r1][c1] = v1
    
#print(val)
    
for i in range(1,r+1):
    for j in range(1,c+1):
        for k in range(num):
            dp[i][j][0] = max(dp[i][j][0],dp[i-1][j][k])
            dp[i][j][1] = max(dp[i][j][1],dp[i-1][j][k]+val[i][j])
            dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k])
            if k == 0:
                continue
            dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k-1]+val[i][j])

ans = 0
for i in range(num):
    ans = max(ans,dp[r][c][i])            
#print(dp)
print(ans)

Submission status: Time Limit Exceeded

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

num = 4

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

val = [[0 for i in range(c+1)] for j in range(r+1)]

for i in range(k):
    r1,c1,v1 = map(int,input().split())
    val[r1][c1] = v1
    
#print(val)
    
for i in range(1,r+1):
    for j in range(1,c+1):
        for k in range(num):
            dp[i][j][0] = max(dp[i][j][0],dp[i-1][j][k])
            dp[i][j][1] = max(dp[i][j][1],dp[i-1][j][k]+val[i][j])
            dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k])
            if k == 0:
                continue
            dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k-1]+val[i][j])

ans = 0
for i in range(num):
    ans = max(ans,dp[r][c][i])            
#print(dp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
## coding: UTF-8
R,C,K = map(int,input().split())
rcv = []
for i in range(K):
    rcv.append(list(map(int,input().split())))

#print(rcv)

#available = [False] * (R*C+1) #アイテムの有無を示す
item = [0] * (R*C+1)
for i in range(K):
    index = (rcv[i][0] - 1) * C + (rcv[i][1] - 1) +1
    #available[index] = True
    item[index] = rcv[i][2]
#print(available, item)


def solver(R,C,K,rcv):
    #その場所にいる段階での最大スコアを出力
    #その行で獲得した個数も格納
    #DPの都合上0番目の要素を追加
    #グリッドは1次元で処理(1行目は1~C, 2行目はC+1~2C, ...)
    dp = []
    for i in range(R*C+1):
        dp.append([0] * 4)
    #print(dp)
    for i in range(1, R*C+1):
        #print(item[i])
        if(i == 1):
            #左上なら
            #dp[i][0] = dp[i-1][0] #左から(何も持ってこない)
            #if(available[i]):
            #itemがある場合は取得するときと取得しない二通りに分けられる
            dp[i][1] = dp[i-1][0] + item[i]
        elif(i <= C):
            #左上以外の上(左からくる場合に限られる)
            dp[i][0] = dp[i-1][0] #itemを取得しない場合
            #if(available[i]):
            dp[i][1] = max(dp[i-1][1], dp[i-1][0] + item[i])
                #if(dp[i-1][1] > 0): #左ですでに一個以上所持している場合にのみ、このマスで二個目ということが可能
            dp[i][2] = max(dp[i-1][2], dp[i-1][1] + item[i])
                #else:
                    #dp[i][2] = 0
                #if(dp[i-1][2] > 0): #左ですでに二個以上所持している場合にのみ、このマスで三個目ということが可能
            dp[i][3] = max(dp[i-1][3], dp[i-1][2] + item[i])
                #else:
                    #dp[i][3] = 0
            #else:
                #dp[i][1] = dp[i-1][1]
                #dp[i][2] = dp[i-1][2]
                #dp[i][3] = dp[i-1][3]
        elif(i % C == 1):
            #左上以外の左(上からくる場合に限られる)
            dp[i][0] = max(dp[i-C]) #下に降りてくる場合は、行で取得したアイテム数はリセットされる
            #if(available[i]):
                #dp[i][1] = max(dp[i-C]) + item[i]
            dp[i][1] = dp[i][0] + item[i]
        else:
            #左でも上でもない場合
            dp[i][0] = max(dp[i-1][0], max(dp[i-C])) #左からくる場合は0限定だが、上からくる場合は、上の行で何個拾っててもいい
            #if(available[i]):
                #dp[i][1] = max(dp[i-1][1], dp[i-1][0] + item[i], max(dp[i-C]) + item[i] ) #左から一個持った状態で来て拾わないor左から何も持たずに来て拾うor上から来て(所持数関係無し)拾う
            dp[i][1] = max(dp[i-1][1], dp[i][0] + item[i])
                #if(dp[i-1][1] > 0): #左ですでに一個以上所持している場合にのみ、このマスで二個目ということが可能
            dp[i][2] = max(dp[i-1][2], dp[i-1][1] + item[i]) #上から来て二個目は不可能
                #else:
                    #dp[i][2] = 0
                #if(dp[i-1][2] > 0):
            dp[i][3] = max(dp[i-1][3], dp[i-1][2] + item[i])
                #else:
                    #dp[i][3] = 0
            #else:
                #dp[i][1] = dp[i-1][1]
                #dp[i][2] = dp[i-1][2]
                #dp[i][3] = dp[i-1][3]

         

        #print(i, dp)
    print(max(dp[R*C]))


solver(R,C,K,rcv)
#print(-1)

Submission status: Time Limit Exceeded

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

def solve():
    INF = float('inf')

    def max2(x, y): return x if x >= y else y

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

    dpMax = [0]*(C+1)
    for i in range(1, R+1):
        dp0 = [0]*(C+1)
        dp1 = [-INF]*(C+1)
        dp2 = [-INF]*(C+1)
        dp3 = [-INF]*(C+1)
        for j in range(1, C+1):
            V = Vss[i][j]
            dp0[j] = max2(dp0[j-1], dpMax[j])
            dp1[j] = max2(dp0[j] + V, dp1[j-1])
            dp2[j] = max2(dp1[j-1] + V, dp2[j-1])
            dp3[j] = max2(dp2[j-1] + V, dp3[j-1])
            dpMax[j] = max(dp0[j], dp1[j], dp2[j], dp3[j])

    ans = dpMax[C]
    print(ans)


solve()

Submission status: Time Limit Exceeded

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

def solve():
    INF = float('inf')

    def max2(x, y): return x if x >= y else y

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

    dp = [[[-INF]*(4) for j 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
    dpMax = [[0]*(C+1) for _ in range(R+1)]

    for i in range(1, R+1):
        for j in range(1, C+1):
            V = Vss[i][j]
            dp[i][j][0] = max2(dp[i][j-1][0], dpMax[i-1][j])
            dp[i][j][1] = max2(dp[i][j][0] + V, dp[i][j-1][1])
            dp[i][j][2] = max2(dp[i][j-1][1] + V, dp[i][j-1][2])
            dp[i][j][3] = max2(dp[i][j-1][2] + V, dp[i][j-1][3])
            dpMax[i][j] = max(dp[i][j])

    ans = dpMax[R][C]
    print(ans)


solve()

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
input = stdin.readline
(R,C,K) = map(int, input().split())
rcv = [list(map(int, input().split())) for _ in range(K)]

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

for r,c,v in rcv:
    grids[r-1][c-1] = v

from collections import defaultdict
dp = defaultdict(int)

for r in range(R):
    for c in range(C):
        tmp = value = grids[r][c]
        for i in range(1,4):
            if c:
                tmp = max(tmp, dp[r,c-1,i])
                if i > 1:
                    tmp = max(tmp, dp[r,c-1,i-1] + value)
            if r and i == 1:
                tmp = max(tmp, dp[r-1,c,3] + value)
            dp[r,c,i] = tmp

print(dp[R-1,C-1,3])