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
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],max(l[i-1][j]))
        l[i][j][3]=max(l[i][j-1][2]+m[i][j],l[i][j-1][3],max(l[i-1][j]))
print(max(l[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
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]))

Submission status: Time Limit Exceeded

Solution code:
row, column, k = map(int, input().split())

my_d = dict()

for _ in range(k):
    r, c, v = map(int, input().split())
    if (r-1, c-1) in my_d:
        my_d[(r-1, c-1)].append(v)
    else:
        my_d[(r-1, c-1)] = [v]

for item in my_d:
    my_d[item].sort()

dp = [[[0 for _ in range(4)] for _ in range(column)] for _ in range(row)]

for i in range(row):
    for j in range(column):
        for kosu in range(4):
            if kosu == 0:
                dp[i][j][0] = 0 if i == 0 else max(dp[i-1][j])
            elif kosu == 1:
                cand1 = 0 if i == 0 else max(dp[i-1][j])
                cand2 = 0 if j == 0 else dp[i][j-1][1]
                cand3 = 0 if (i, j) not in my_d else my_d[(i, j)][-1]
                dp[i][j][1] = max(cand1 + cand3, cand2)
            elif kosu == 2:
                cand1 = 0 if i == 0 else max(dp[i-1][j])
                cand2 = 0 if j == 0 else dp[i][j-1][1]
                cand3 = 0 if (i, j) not in my_d else my_d[(i, j)][-1]
                cand4 = 0 if i == 0 else max(dp[i-1][j])
                cand5 = 0 if j == 0 else dp[i][j-1][2]
                cand6 = 0 if ((i, j) not in my_d or len(
                    my_d[(i, j)]) < 2) else sum(my_d[(i, j)][-2:])
                dp[i][j][2] = max(cand5, cand6 + cand4, cand2 + cand3)
            elif kosu == 3:
                cand1 = 0 if i == 0 else max(dp[i-1][j])
                cand2 = 0 if j == 0 else dp[i][j-1][1]
                cand3 = 0 if (i, j) not in my_d else my_d[(i, j)][-1]
                cand4 = 0 if i == 0 else max(dp[i-1][j])
                cand5 = 0 if j == 0 else dp[i][j-1][2]
                cand6 = 0 if ((i, j) not in my_d or len(
                    my_d[(i, j)]) < 2) else sum(my_d[(i, j)][-2:])
                cand7 = 0 if i == 0 else max(dp[i-1][j])
                cand8 = 0 if j == 0 else dp[i][j-1][3]
                cand9 = 0 if ((i, j) not in my_d or len(
                    my_d[(i, j)]) < 3) else sum(my_d[(i, j)][-3:])
                dp[i][j][3] = max(cand8, cand7+cand9, cand5+cand3, cand2+cand6)

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

Submission status: Time Limit Exceeded

Solution code:
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())


def main():

    R, C, K = in_nn()

    grid = [[-1 for _ in range(C)] for _ in range(R)]

    for i in range(K):
        r, c, v = in_nn()
        r, c = r - 1, c - 1
        grid[r][c] = v

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

    if grid[0][0] != -1:
        dp[0][0][1] = grid[0][0]

    for y in range(R):
        for x in range(C):

            # 選ばない
            if 0 <= y - 1:
                for i in range(4):
                    dp[y][x][0] = max(dp[y][x][0], dp[y - 1][x][i])
            if 0 <= x - 1:
                for i in range(4):
                    dp[y][x][i] = max(dp[y][x][i], dp[y][x - 1][i])

            # 選ぶ
            if grid[y][x] != -1:
                if 0 <= y - 1:
                    for i in range(4):
                        dp[y][x][1] = max(dp[y][x][1], dp[y - 1][x][i] + grid[y][x])
            if 0 <= x - 1:
                for i in range(1, 4):
                    dp[y][x][i] = max(dp[y][x][i], dp[y][x - 1][i - 1] + grid[y][x])

    # for y in range(R):
    #     for x in range(C):
    #         print(dp[y][x])
    print(max(dp[-1][-1]))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from bisect import *
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:
# pypy
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

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 = {}
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)]
def get(r, c, k):
    try:
        return dp[r][c][k]
    except:
        return 0


if (0, 0) in rc2v:
    dp[0][0][1] = rc2v[(0, 0)]

for c in range(1, C):
    if (0, c) in rc2v:
        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)])
    else:
        for k in range(1, 4):
            dp[0][c][k] = dp[0][c-1][k]

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]))
        if (r, c) in rc2v:
            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)])
        else:
            for k in range(1, 4):
                dp[r][c][k] = dp[r][c-1][k]


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

Submission status: Time Limit Exceeded

Solution code:
import sys
read = sys.stdin.buffer.read
readlines = sys.stdin.buffer.readlines
input = sys.stdin.buffer.readline
H, W, K = map(int, input().split())
B = [[0]*W for _ in [0]*H]

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

dp = [[[0]*4 for _ in [0]*(W+1)] for _ in [0]*(H+1)]

for i in range(H):
    for j in range(W):
        v = B[i][j]
        if v:
            dp[i+1][j+1][0] = max(dp[i+1][j][0], max(dp[i][j+1]))

            dp[i+1][j+1][1] = max(dp[i+1][j][1],
                                  max(dp[i][j+1])+v, dp[i+1][j][0]+v)

            dp[i+1][j+1][2] = max(dp[i+1][j][2], dp[i+1][j][1]+v)

            dp[i+1][j+1][3] = max(dp[i+1][j][3], dp[i+1][j][2]+v)
        else:
            dp[i+1][j+1][0] = max(dp[i+1][j][0], max(dp[i][j+1]))
            dp[i+1][j+1][1] = dp[i+1][j][1]
            dp[i+1][j+1][2] = dp[i+1][j][2]
            dp[i+1][j+1][3] = dp[i+1][j][3]
print(max(dp[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
# dp[r][c][p] := 位置r, cに到着し、該当行で拾ったアイテムがp個の時の、最大価値
# r = 0〜R, c = 0〜C, p = 0〜3

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

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

item_values = {}

for item in items:
    item_values[(item[0], item[1])] = item[2]

for r in range(1, R+1):
    for c in range(1, C+1):
        value_here = item_values.get((r, c), 0)

        if value_here == 0:
            dp[r][c][0] = max(
                dp[r][c-1][0],
                max(dp[r-1][c])
            )
            dp[r][c][1] = dp[r][c-1][1]
            dp[r][c][2] = dp[r][c-1][2]
            dp[r][c][3] = dp[r][c-1][3]
        
        else:
            dp[r][c][0] = max(
                dp[r][c-1][0],
                max(dp[r-1][c])
            )
            dp[r][c][1] = max([
                dp[r][c-1][1],
                dp[r][c-1][0] + value_here,
                max(dp[r-1][c]) + value_here
            ])

            dp[r][c][2] = max(dp[r][c-1][2], dp[r][c-1][1] + value_here)
            dp[r][c][3] = max(dp[r][c-1][3], dp[r][c-1][2] + value_here)
            
print(max(dp[R][C]))

# print(dp)

Submission status: Time Limit Exceeded

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

v = [[0 for i in range(c)] for j in range(r)]

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

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

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

r,c,k = map(int,readline().split())
items = [[0]*c for _ in range(r)]
for i in range(k):
    a,b,v = map(int,readline().split())
    a,b = a-1,b-1
    items[a][b] = v

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

#process1
#移動は→↓の２通りのみなので、その方向に探索していけば良い。
for i in range(1,r+1):
    for j in range(1,c+1):
        if items[i-1][j-1]:
            dp[i][j][0] = max(max(dp[i-1][j]),dp[i][j-1][0])
            dp[i][j][1] = max(max(dp[i-1][j])+items[i-1][j-1],dp[i][j-1][1],dp[i][j-1][0]+items[i-1][j-1])
            dp[i][j][2] = max(dp[i][j-1][2],dp[i][j-1][1]+items[i-1][j-1])
            dp[i][j][3] = max(dp[i][j-1][3],dp[i][j-1][2]+items[i-1][j-1])
        else:
            dp[i][j][0] = max(max(dp[i-1][j]),dp[i][j-1][0])
            dp[i][j][1] = dp[i][j-1][1]
            dp[i][j][2] = dp[i][j-1][2]
            dp[i][j][3] = dp[i][j-1][3]

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

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
import sys
from collections import defaultdict
def LI(): return [int(x) for x in sys.stdin.readline().split()]

def solve():
    h,w,k = LI()
    S = h*w
    if w == 1:
        d = [w]
    else:
        d = [w,1]
    s = [0]*S
    for _ in range(k):
        y,x,v = LI()
        y -= 1
        x -= 1
        s[y*w+x] = v
    dp = [[-float("inf")]*4 for _ in range(S)]
    dp[0][0] = 0
    sc = s[0]
    if sc != 0:
        dp[0][1] = sc

    for i in range(S):
        for n in range(4):
            dyx = dp[i][n]
            for ind,di in enumerate(d):
                if not ind and i+w >= S:
                    continue
                elif ind and i%w == w-1:
                    continue
                j = i+di
                if not ind:
                    nn = 0
                else:
                    nn = n
                if dp[j][nn] < dyx:
                    dp[j][nn] = dyx
                if nn < 3:
                    nsc = s[j]
                    if nsc != 0:
                        nn += 1
                        ndp = dyx+nsc
                        if dp[j][nn] < ndp:
                            dp[j][nn] = ndp
    print(max(dp[-1]))
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
r, c, k = map(int, input().split())
it = [[0] * c for _ in range(r)]
for _ in range(k):
    rr, cc, vv = map(int, input().split())
    rr -= 1
    cc -= 1
    it[rr][cc] = vv

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

dp[0][0][1] = it[0][0]
for i in range(r):
    for j in range(c):
        if i != 0:
            dp[i][j][0] = max(dp[i-1][j])
            dp[i][j][1] = max(dp[i-1][j]) + it[i][j]
        if j != 0:
            dp[i][j][0] = max(dp[i][j][0], dp[i][j-1][0])
            for k in range(1, 4):
                dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k],
                                  dp[i][j-1][k-1]+it[i][j])
print(max(dp[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
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)]
for x,y,z in a:
    dp[x][y][4]=z
for i in range(1,r+1):
    for j in range(1,c+1):
        v=dp[i][j][4]
        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]))

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(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):
        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:

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



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

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

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

ans=0
stk=[(0,0,0,3)]
while stk:
    i,j,tt,k=stk.pop()
    ntt,nk=tt,k
    if k>0:
        ntt+=grid[i][j]
        nk=k-1
    if i+1==R and j+1==C:
        ans=max(ans,ntt)
        continue
    for ni,nj in (i,j+1),(i+1,j):
        if not (ni<R and nj<C):
            continue
        if ni!=i:
            k=nk=3
        stk.append((ni,nj,tt,k))
        if tt!=ntt:
            stk.append((ni,nj,ntt,nk))


print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys


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

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

    items = [[0] * (c + 1) for _ in range(r + 1)]
    for _ in range(k):
        i, j, v = map(int, input().split())
        items[i][j] = v

    # dp[i][j][m] = (i行j列時点で、i行でm個のitemを取得している時の価値の最大値)
    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 m in range(4):
                dp[i][j][m] = max(dp[i - 1][j][3], dp[i][j - 1][m])
            if items[i][j] > 0:
                for m in [2, 1, 0]:
                    dp[i][j][m + 1] = max(dp[i][j][m + 1],
                                          dp[i][j][m] + items[i][j])

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


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):
    new_dp = [row.copy() for row in dp]
    while index < K and rcvs[index][1] == c:
        x, _, v = rcvs[index]
        if new_dp[3][x] < dp[2][x] + v:
            new_dp[3][x] = dp[2][x] + v
        if new_dp[2][x] < dp[1][x] + v:
            new_dp[2][x] = dp[1][x] + v
        if new_dp[1][x] < dp[0][x] + v:
            new_dp[1][x] = dp[0][x] + v
        index += 1
        for r in range(R):
            new_dp[0][r+1] = max(new_dp[0][r], new_dp[1][r], new_dp[2][r], new_dp[3][r])
        dp = new_dp
        #print(dp)   
    
print(max(max(row) for row in dp))

Submission status: Time Limit Exceeded

Solution code:
import sys

input=sys.stdin.readline

R,C,K=map(int,input().split())
item={}
for i in range(K):
    r,c,v=map(int,input().split())
    item[r-1,c-1]=0
    item[r-1,c-1]=v

dp=[[0 for i in range(3)] for j in range(C)]

if (R-1,C-1) in item:
    dp[C-1][0]=item[R-1,C-1]
    dp[C-1][1]=item[R-1,C-1]
    dp[C-1][2]=item[R-1,C-1]

for j in range(C-2,-1,-1):
    if (R-1,j) in item:
        dp[j][0]=max(dp[j+1][1]+item[R-1,j],dp[j+1][0])
        dp[j][1]=max(dp[j+1][2]+item[R-1,j],dp[j+1][1])
        dp[j][2]=max(item[R-1,j],dp[j+1][2])
    else:
        dp[j][0]=dp[j+1][0]
        dp[j][1]=dp[j+1][1]
        dp[j][2]=dp[j+1][2]

for i in range(R-2,-1,-1):
    ndp=[[0 for i in range(3)] for j in range(C)]
    if (i,C-1) in item:
        ndp[C-1][0]=dp[C-1][0]+item[i,C-1]
        ndp[C-1][1]=dp[C-1][0]+item[i,C-1]
        ndp[C-1][2]=dp[C-1][0]+item[i,C-1]
    else:
        ndp[C-1][0]=dp[C-1][0]
        ndp[C-1][1]=dp[C-1][0]
        ndp[C-1][2]=dp[C-1][0]
    for j in range(C-2,-1,-1):
        if (i,j) in item:
            ndp[j][0]=max(max(dp[j][0],ndp[j+1][1])+item[i,j],ndp[j+1][0])
            ndp[j][1]=max(max(dp[j][0],ndp[j+1][2])+item[i,j],ndp[j+1][1])
            ndp[j][2]=max(dp[j][0]+item[i,j],ndp[j+1][2])
        else:
            ndp[j][0]=max(dp[j][0],ndp[j+1][0])
            ndp[j][1]=max(dp[j][0],ndp[j+1][1])
            ndp[j][2]=max(dp[j][0],ndp[j+1][2])
    dp=ndp

print(dp[0][0])

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):
        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:

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



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:

import sys
inf=float('inf')
ans=0
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()
def LI():return [int(i) for i in input().split()]
h,w,k=LI()
v=[[0]*(w+1) for i in range(h+1)]
for i in range(k):
    a,b,x=LI()
    v[a][b]=x

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

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 and dp[i][j][1]<up_max+v[i][j]:
            dp[i][j][1]=up_max+v[i][j]
        if dp[i][j][0]<dp[i][j-1][0]:
            dp[i][j][0]=dp[i][j-1][0]
        
        dp[i][j][3]=max(dp[i][j][3],dp[i][j-1][3],dp[i][j-1][3-1]+v[i][j])
        dp[i][j][2]=max(dp[i][j][2],dp[i][j-1][2],dp[i][j-1][2-1]+v[i][j])
        dp[i][j][1]=max(dp[i][j][1],dp[i][j-1][1],dp[i][j-1][1-1]+v[i][j])
            

ans=max(dp[h][w])
print(ans)

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())
        rr -= 1
        cc -= 1
        tizu[rr * c + cc] = 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][0] = tmp
                dp[j][1] = tmp + v
                dp[j][2] = 0
                dp[j][3] = 0
            if j != 0:
                tmp0 = dp[j - 1][0]
                tmp1 = dp[j - 1][1]
                tmp2 = dp[j - 1][2]
                dp[j][0] = max(dp[j][0], tmp0)
                dp[j][1] = max(dp[j][1], tmp1, tmp0 + v)
                dp[j][2] = max(tmp2, tmp1 + v)
                dp[j][3] = max(dp[j - 1][3], tmp2 + v)
    print(max(dp[-1]))
    
main()

Submission status: Time Limit Exceeded

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

import collections
import sys
input=sys.stdin.readline

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

Submission status: Time Limit Exceeded

Solution code:
import sys


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

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

    items = [[0] * (c + 1) for _ in range(r + 1)]
    for _ in range(k):
        i, j, v = map(int, input().split())
        items[i][j] = v

    # dp[i][j][m] = (i行j列時点で、i行でm個のitemを取得している時の価値の最大値)
    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 m in range(4):
                dp[i][j][m] = max(dp[i - 1][j][3], dp[i][j - 1][m])
            for m in reversed(range(3)):
                dp[i][j][m + 1] = max(dp[i][j][m + 1],
                                      dp[i][j][m] + items[i][j])

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


if __name__ == '__main__':
    main()