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:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal



def run():
    R,C,K = map(int, sysread().split())
    Rs = set()
    Cs = set()
    vals = []
    for i in range(K):
        r, c, v = map(int, sysread().split())
        vals.append((r, c, v))
        Rs.add(r)
        Cs.add(c)
    Rs = sorted(list(Rs))
    Cs = sorted(list(Cs))
    r_idx = {r:i+1 for i, r in enumerate(Rs)}
    c_idx = {c:i+1 for i, c in enumerate(Cs)}
    MAP = [[0] * (len(Cs)+1) for _ in range(len(Rs)+1)]
    for r,c,v in vals:
        rn = r_idx[r]
        cn = c_idx[c]
        MAP[rn][cn] = v

    dp = [[[0] * 4 for _ in range(len(Cs)+1)] for i in range(len(Rs)+1)]

    for i in range(1, len(Rs)+1):
        for j in range(1, len(Cs)+1):
            for k in range(4):
                dp[i][j][0] = max(dp[i][j][0], dp[i-1][j][k])
                if MAP[i][j]:
                    dp[i][j][1] = max(dp[i][j][1], dp[i-1][j][k]+MAP[i][j])

                dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k])
                if MAP[i][j] and k < 3:
                    dp[i][j][k+1] = max(dp[i][j][k+1], dp[i][j-1][k] + MAP[i][j])
    #print(dp)
    #for m in MAP:
    #   print(m)
    print(max(dp[len(Rs)][len(Cs)]))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

def main():
    r,c,k=MI()
    dp=[[[-inf]*4 for j in range(c)]  for i in range(r)]
    val=[[0]*c for i in range(r)]
    for i in range(k):
        x,y,v=MI()
        val[x-1][y-1]=v
    if val[0][0]>0:
        dp[0][0][1]=val[0][0]
        dp[0][0][0]=0
    else:
        dp[0][0][0]=0
    #print(dp)
    for i in range(r):
        for j in range(c):
            if i<r-1:
                if val[i+1][j]>0:
                    for k in range(4):
                        dp[i+1][j][1]=max(dp[i+1][j][1],dp[i][j][k]+val[i+1][j])
                for k in range(4):
                    dp[i+1][j][0]=max(dp[i+1][j][0],dp[i][j][k])                 
            if j<c-1:
                if val[i][j+1]>0:
                    for k in range(1,4):
                        dp[i][j+1][k]=max(dp[i][j+1][k],dp[i][j][k-1]+val[i][j+1])
                for k in range(4):
                    dp[i][j+1][k]=max(dp[i][j+1][k],dp[i][j][k])
    print(max(dp[-1][-1]))
if __name__=="__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import defaultdict
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def make_grid_int(h, w, num): return [[int(num)] * w for _ in range(h)]


def main():
    R, C, K = NMI()
    grid = make_grid_int(R, C, 0)
    for i in range(K):
        r, c, v = NMI()
        grid[r-1][c-1] = v

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

    for r in range(R+1):
        for c in range(C+1):
            for i in range(4):
                now = dp[r][c][i]
                try:
                    val = grid[r][c]
                except:
                    val = 0

                if i == 3:
                    # 取らずに下
                    dp[r + 1][c][0] = max(now, dp[r + 1][c][0])
                    continue

                # 取って下
                dp[r+1][c][0] = max(now + val, dp[r+1][c][0])
                # 取らずに下
                dp[r+1][c][0] = max(now, dp[r+1][c][0])
                # 取って横
                dp[r][c+1][i+1] = max(now + val, dp[r][c+1][i+1])
                # 取らずに横
                dp[r][c+1][i] = max(now, dp[r][c+1][i])

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
R,C,K = map(int,input().split())
RCV = [tuple(map(int,input().split())) for i in range(K)]

goods = [dict() for _ in range(R)]
for r,c,v in RCV:
    r,c = r-1,c-1
    goods[r][c] = v

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

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

Submission status: Time Limit Exceeded

Solution code:
def main():
    r, c, k = map(int, input().split())
    d = dict()
    for _ in range(k):
        t1, t2, t3 = map(int, input().split())
        d[(t1-1, t2-1)] = t3
    dp = [[[0]*4 for _ in [0]*c] for _ in [0]*r]
    if (0, 0) in d:
        dp[0][0][1] = d[(0, 0)]
    for x in range(r):
        for y in range(c):
            for z in range(4):
                if y != c-1:
                    if z != 3:
                        if (x, y+1) in d:
                            dp[x][y+1][z+1] = max(dp[x][y+1]
                                                  [z+1], dp[x][y][z]+d[(x, y+1)])
                    dp[x][y+1][z] = max(dp[x][y+1][z], dp[x][y][z])
            if x != r-1:
                if (x+1, y) in d:
                    dp[x+1][y][1] = max(dp[x+1][y][1],
                                        max(dp[x][y])+d[(x+1, y)])
                dp[x+1][y][0] = max(dp[x+1][y][0], max(dp[x][y]))
    print(max(dp[r-1][c-1]))


main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    r, c, k = map(int, input().split())
    d = dict()
    for _ in range(k):
        t1, t2, t3 = map(int, input().split())
        d[(t1-1, t2-1)] = t3
    dp = [[[0]*4 for _ in [0]*c] for _ in [0]*r]
    if (0, 0) in d:
        dp[0][0][1] = d[(0, 0)]
    for x in range(r):
        for y in range(c):
            for z in range(4):
                if x != r-1:
                    if (x+1, y) in d:
                        dp[x+1][y][1] = max(dp[x+1][y][1],
                                            dp[x][y][z]+d[(x+1, y)])
                    dp[x+1][y][0] = max(dp[x+1][y][0], dp[x][y][z])
                if y != c-1:
                    if z != 3:
                        if (x, y+1) in d:
                            dp[x][y+1][z+1] = max(dp[x][y+1]
                                                  [z+1], dp[x][y][z]+d[(x, y+1)])
                    dp[x][y+1][z] = max(dp[x][y+1][z], dp[x][y][z])
    print(max(dp[r-1][c-1]))


main()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal

def appmax(dp, idxes1, val):
    i, j, k = idxes1
    dp[i][j][k] = max(dp[i][j][k], val)

INF = 1 << 63


def run():
    R,C,K = map(int, sysread().split())
    Rs = set()
    Cs = set()
    vals = []
    for i in range(K):
        r, c, v = map(int, sysread().split())
        vals.append((r, c, v))
        Rs.add(r)
        Cs.add(c)
    Rs = sorted(list(Rs))
    Cs = sorted(list(Cs))
    r_idx = {r:i+1 for i, r in enumerate(Rs)}
    c_idx = {c:i+1 for i, c in enumerate(Cs)}
    MAP = [[0] * (len(Cs)+1) for _ in range(len(Rs)+1)]
    for r,c,v in vals:
        rn = r_idx[r]
        cn = c_idx[c]
        MAP[rn][cn] = v

    dp = [[[0] * 4 for _ in range(len(Cs)+1)] for i in range(len(Rs)+1)]

    for i in range(1, len(Rs)+1):
        for j in range(1, len(Cs)+1):
            for k in range(4):
                appmax(dp, (i, j, 0), dp[i-1][j][k])
                if MAP[i][j]:
                    appmax(dp, (i, j, 1), dp[i-1][j][k] + MAP[i][j])
                appmax(dp, (i, j, k), dp[i][j-1][k])
                if MAP[i][j] and k < 3:
                    appmax(dp, (i, j, k+1), dp[i][j-1][k] + MAP[i][j])
    #print(dp)
    #for m in MAP:
    #    print(m)
    print(max(dp[len(Rs)][len(Cs)]))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

r,c,k=MI()
dp=[[[-inf]*4 for j in range(c)]  for i in range(r)]
val=[[0]*c for i in range(r)]
for i in range(k):
    x,y,v=MI()
    val[x-1][y-1]=v
if val[0][0]>0:
    dp[0][0][1]=val[0][0]
    dp[0][0][0]=0
else:
    dp[0][0][0]=0
#print(dp)
for i in range(r):
    for j in range(c):
        if i<r-1:
            if val[i+1][j]>0:
                for k in range(4):
                    dp[i+1][j][1]=max(dp[i+1][j][1],dp[i][j][k]+val[i+1][j])
            for k in range(4):
                dp[i+1][j][0]=max(dp[i+1][j][0],dp[i][j][k])                 
        if j<c-1:
            if val[i][j+1]>0:
                for k in range(1,4):
                    dp[i][j+1][k]=max(dp[i][j+1][k],dp[i][j][k-1]+val[i][j+1])
            for k in range(4):
                dp[i][j+1][k]=max(dp[i][j+1][k],dp[i][j][k])
#print(val)
print(max(dp[-1][-1]))
#print(dp)

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    my_input = sys.stdin.readline
    H, W, K = map(int, my_input().split())
    V = [[0] * W for _ in range(H)]
    for i in range(K):
        h, w, v = map(int, my_input().split())
        h, w = h - 1, w - 1
        V[h][w] = v

    # dp[h][w][x] := h行w列にいて、h行からx個アイテムを拾っている時の価値の総和の最大値
    dp = [[[0] * 4 for j in range(W + 1)] for i in range(H + 1)]
    for h in range(1, H + 1):
        for w in range(1, W + 1):
            for k in range(1, 4):
                dp[h][w][k] = max(
                    dp[h][w][k],
                    dp[h - 1][w][-1],
                    dp[h - 1][w][-1] + V[h - 1][w - 1],
                    dp[h][w - 1][k],
                    dp[h][w - 1][k - 1] + V[h - 1][w - 1])

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
H, W, K = map(int, input().split())
V = [[0] * W for _ in range(H)]
for i in range(K):
    h, w, v = map(int, input().split())
    h, w = h - 1, w - 1
    V[h][w] = v

# dp[h][w][x] := h行w列にいて、h行からx個アイテムを拾っている時の価値の総和の最大値
dp = [[[0] * 4 for j in range(W + 1)] for i in range(H + 1)]
for h in range(1, H + 1):
    for w in range(1, W + 1):
        for k in range(1, 4):
            dp[h][w][k] = max(
                dp[h][w][k],
                dp[h - 1][w][-1],
                dp[h - 1][w][-1] + V[h - 1][w - 1],
                dp[h][w - 1][k],
                dp[h][w - 1][k - 1] + V[h - 1][w - 1])

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

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal

def appmax(dp, idxes1, val):
    i, j, k = idxes1
    dp[i][j][k] = max(dp[i][j][k], val)

INF = 1 << 63


def run():
    R,C,K = map(int, sysread().split())
    MAP = [[0] * (C+1) for _ in range(R+1)]
    for i in range(K):
        r, c, v = map(int, sysread().split())
        MAP[r][c] = v

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

    for i in range(1, R+1):
        for j in range(1, C+1):
            for k in range(4):
                appmax(dp, (i, j, 0), dp[i-1][j][k])
                if MAP[i][j]:
                    appmax(dp, (i, j, 1), dp[i-1][j][k] + MAP[i][j])
                appmax(dp, (i, j, k), dp[i][j-1][k])
                if MAP[i][j] and k < 3:
                    appmax(dp, (i, j, k+1), dp[i][j-1][k] + MAP[i][j])
    #print(dp)
    #for m in MAP:
    #    print(m)
    print(max(dp[R][C]))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal

def appmax(dp, idxes1, val):
    i, j, k = idxes1
    dp[i][j][k] = max(dp[i][j][k], val)

INF = 1 << 63


def run():
    R,C,K = map(int, sysread().split())
    MAP = [[0] * (C+1) for _ in range(R+1)]
    for i in range(K):
        r, c, v = map(int, sysread().split())
        MAP[r][c] = v

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

    for i in range(R+1):
        for j in range(C+1):
            for k in range(4):
                if i < R:
                    appmax(dp, (i+1, j, 0), dp[i][j][k])
                    if MAP[i+1][j]:
                        appmax(dp, (i+1, j, 1), dp[i][j][k] + MAP[i+1][j])
                if j < C:
                    appmax(dp, (i, j+1, k), dp[i][j][k])
                    if MAP[i][j+1] and k < 3:
                        appmax(dp, (i, j+1, k+1), dp[i][j][k] + MAP[i][j+1])
    #print(dp)
    #for m in MAP:
    #    print(m)
    print(max(dp[R][C]))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy
from collections import defaultdict


def main():
    R, C, K = map(int, input().split())
    rcv = [list(map(int, input().split())) for _ in range(K)]

    d = defaultdict(list)
    for r, c, v in rcv:
        d[r].append([c, v])

    for r in d.keys():
        d[r].sort()

    dp = [0] * (C + 1)

    for r, li in sorted(d.items()):
        prev = deepcopy(dp)
        for i, (cs, vs) in enumerate(li):
            mx = 0
            for cg, vg in li[i+1:]:
                val = vs + mx + vg
                dp[cg] = max(dp[cg], prev[cs] + val)
                mx = max(mx, vg)

            dp[cs] = max(dp[cs], prev[cs] + vs)

        for c in range(C):
            dp[c+1] = max(dp[c+1], dp[c])

    ans = dp[C]
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    # 入力
    R, C, K = map(int, input().split())
    point_map = [dict() for _ in range(R+1)]  # [[0]*(C+1) for _ in range(R+1)]
    max_point = [[[0]*4 for _ in range(C + 1)]
                 for _ in range(R + 1)]

    for i in range(K):
        _r, _c, _k = map(int, input().split())
        point_map[_r][_c] = _k

    j_range = list(range(1, C + 1))
    for i in range(1, R+1):
        im = i-1
        for j in j_range:
            jm = j - 1
            mxi = max_point[i]
            mxim = max_point[i-1]
            mxij = mxi[j]
            mxijm = mxi[jm]
            point = point_map[i].get(j, 0)
            mxij[0] = max(
                mxijm[0],
                mxim[j][0],
                mxim[j][1],
                mxim[j][2],
                mxim[j][3]
            )

            mxij[1] = mxij[0] + point
            if mxij[1] < mxijm[1]:
                mxij[1] = mxijm[1]

            mxij[2] = mxijm[1] + point
            if mxij[2] < mxijm[2]:
                mxij[2] = mxijm[2]
            mxij[3] = mxijm[2] + point
            if mxij[3] < mxijm[3]:
                mxij[3] = mxijm[3]
            # print(i, j, max_point[i][j])

    print(max(max_point[R][C]))


main()

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy
from collections import defaultdict

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

d = defaultdict(list)
for r, c, v in rcv:
    d[r].append([c, v])

for r in d.keys():
    d[r].sort()

dp = [0] * (C + 1)

for r, li in sorted(d.items()):
    prev = deepcopy(dp)
    for i, (cs, vs) in enumerate(li):
        mx = 0
        for cg, vg in li[i+1:]:
            val = vs + mx + vg
            dp[cg] = max(dp[cg], prev[cs] + val)
            mx = max(mx, vg)

        dp[cs] = max(dp[cs], prev[cs] + vs)

    for c in range(C):
        dp[c+1] = max(dp[c+1], dp[c])

ans = dp[C]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy

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

d = [[] for _ in range(R + 1)]
for r, c, v in rcv:
    d[r].append([c, v])

for r in range(R + 1):
    d[r].sort()

dp = [0] * (C + 1)
for r, li in enumerate(d[1:], 1):
    prev = deepcopy(dp)
    for i, (cs, vs) in enumerate(li):
        mx = 0
        for cg, vg in li[i+1:]:
            val = vs + mx + vg
            dp[cg] = max(dp[cg], prev[cs] + val)
            mx = max(mx, vg)

        dp[cs] = max(dp[cs], prev[cs] + vs)

    for c in range(C):
        dp[c+1] = max(dp[c+1], dp[c])

ans = dp[C]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# 入力
R, C, K = map(int, input().split())
point_map = [dict() for _ in range(R+1)]  # [[0]*(C+1) for _ in range(R+1)]
max_point = [[[0]*4 for _ in range(C + 1)]
             for _ in range(R + 1)]


for i in range(K):
    _r, _c, _k = map(int, input().split())
    point_map[_r][_c] = _k

for i in range(1, R+1):
    im = i-1
    for j in range(1, C + 1):
        jm = j - 1
        mxi = max_point[i]
        mxim = max_point[i-1]
        mxij = mxi[j]
        mxijm = mxi[jm]
        point = point_map[i].get(j, 0)
        mxij[0] = max(
            mxijm[0],
            mxim[j][0],
            mxim[j][1],
            mxim[j][2],
            mxim[j][3]
        )

        mxij[1] = mxij[0] + point
        if mxij[1] < mxijm[1]:
            mxij[1] = mxijm[1]

        mxij[2] = mxijm[1] + point
        if mxij[2] < mxijm[2]:
            mxij[2] = mxijm[2]
        mxij[3] = mxijm[2] + point
        if mxij[3] < mxijm[3]:
            mxij[3] = mxijm[3]
        # print(i, j, max_point[i][j])

print(max(max_point[R][C]))

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy


def translate(r, c):
    return r * (C + 1) + c


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

d = [[] for _ in range(R + 1)]
for r, c, v in rcv:
    d[r].append([c, v])

for r in range(R + 1):
    d[r].sort()

dp = [[0] * (C + 1) for _ in range(R + 1)]
for r, li in enumerate(d[1:], 1):
    dp[r] = deepcopy(dp[r-1])
    for i, (cs, vs) in enumerate(li):
        mx = 0
        for cg, vg in li[i+1:]:
            val = vs + mx + vg
            dp[r][cg] = max(dp[r][cg], dp[r-1][cs] + val)
            mx = max(mx, vg)

        dp[r][cs] = max(dp[r][cs], dp[r-1][cs] + vs)

    for c in range(C):
        dp[r][c+1] = max(dp[r][c+1], dp[r][c])

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

Submission status: Time Limit Exceeded

Solution code:
# 入力
R, C, K = map(int, input().split())
point_map = [[0]*(C+1) for _ in range(R+1)]
max_point = [[[0]*4 for _ in range(C + 1)]
             for _ in range(R + 1)]


for i in range(K):
    _r, _c, _k = map(int, input().split())
    point_map[_r][_c] = _k

for i in range(1, R+1):
    im = i-1
    for j in range(1, C + 1):
        jm = j - 1
        mxi = max_point[i]
        mxim = max_point[i-1]
        mxij = mxi[j]
        mxijm = mxi[jm]
        point = point_map[i][j]
        mxij[0] = max(
            mxijm[0],
            mxim[j][0],
            mxim[j][1],
            mxim[j][2],
            mxim[j][3]
        )

        mxij[1] = mxij[0] + point
        if mxij[1] < mxijm[1]:
            mxij[1] = mxijm[1]

        mxij[2] = mxijm[1] + point
        if mxij[2] < mxijm[2]:
            mxij[2] = mxijm[2]
        mxij[3] = mxijm[2] + point
        if mxij[3] < mxijm[3]:
            mxij[3] = mxijm[3]
        # print(i, j, max_point[i][j])

print(max(max_point[R][C]))

Submission status: Time Limit Exceeded

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

H,W,K = map(int,readline().split())
from collections import defaultdict
goods = defaultdict(int)
for i in range(K):
  r,c,v = map(int,readline().split())
  r -= 1
  c -= 1
  goods[(r,c)] = v
  
# dp[k][i][j] = マス(i,j)までに、その行でk回(0 - 3)アイテムを拾った場合の最大得点
dp = [[[0 for j in range(W)] for i in range(H)] for k in range(4)]
# 最初のマスにアイテムがある場合の得点を入れておく
if (0,0) in goods:
  dp[1][0][0] = goods[(0,0)]

def show():
  for i in range(len(dp)):
    for j in range(len(dp[i])):
      print("i",i,"j",j,dp[i][j])

for i in range(H):
  for j in range(W):
    if i + 1 < H:
      # 縦の次のマスに行ける場合
      check = False
#      if i == 0 and j == 1:
#        check = True
        
      if (i + 1, j) in goods:
        value = goods[(i + 1, j)]
        # 次のマスにアイテムがあり、それを取る場合
        # 縦に進む場合は、必ず0からスタート
        for k in range(4):
          dp[1][i + 1][j] = max(dp[1][i + 1][j], dp[k][i][j] + value)
      # 次のマスのアイテムがない/取らない場合
      for k in range(4):
        if check:
          print("dp[i + 1][j][k]",dp[i + 1][j][k],"dp[i][j][k]",dp[i][j][k])
        dp[0][i + 1][j] = max(dp[0][i + 1][j], dp[k][i][j])
        if check:
          print("i + 1",i + 1,"j",j,"dp[i + 1][j][0]",dp[i + 1][j][0])
          show()
    if j + 1 < W:
      if (i, j + 1) in goods:
        value = goods[(i, j + 1)]
        # 次のマスにアイテムがあり、それを取る場合
        for k in range(3):
          dp[k + 1][i][j + 1] = max(dp[k + 1][i][j + 1], dp[k][i][j] + value)
      # 次のマスにアイテムがない/取らない場合
      for k in range(4):
        dp[k][i][j + 1] = max(dp[k][i][j + 1], dp[k][i][j])

ans = 0
for i in range(4):
  if dp[i][-1][-1] > ans:
    ans = dp[i][-1][-1]
print(ans)

Submission status: Time Limit Exceeded

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

H,W,K = map(int,readline().split())
from collections import defaultdict
goods = defaultdict(int)
for i in range(K):
  r,c,v = map(int,readline().split())
  r -= 1
  c -= 1
  goods[(r,c)] = v
  
# dp[i][j][k] = マス(i,j)までに、その行でk回(0 - 3)アイテムを拾った場合の最大得点
dp = [[[0] * 4 for j in range(W)] for i in range(H)]
# 最初のマスにアイテムがある場合の得点を入れておく
if (0,0) in goods:
  dp[0][0][1] = goods[(0,0)]

def show():
  for i in range(len(dp)):
    for j in range(len(dp[i])):
      print("i",i,"j",j,dp[i][j])


for i in range(H):
  for j in range(W):
    if i + 1 < H:
      # 縦の次のマスに行ける場合
      check = False
#      if i == 0 and j == 1:
#        check = True
        
      if (i + 1, j) in goods:
        value = goods[(i + 1, j)]
        # 次のマスにアイテムがあり、それを取る場合
        # 縦に進む場合は、必ず0からスタート
        for k in range(4):
          dp[i + 1][j][1] = max(dp[i + 1][j][1], dp[i][j][k] + value)
      # 次のマスのアイテムがない/取らない場合
      for k in range(4):
        if check:
          print("dp[i + 1][j][k]",dp[i + 1][j][k],"dp[i][j][k]",dp[i][j][k])
        dp[i + 1][j][0] = max(dp[i + 1][j][0], dp[i][j][k])
        if check:
          print("i + 1",i + 1,"j",j,"dp[i + 1][j][0]",dp[i + 1][j][0])
          show()
    if j + 1 < W:
      if (i, j + 1) in goods:
        value = goods[(i, j + 1)]
        # 次のマスにアイテムがあり、それを取る場合
        for k in range(3):
          dp[i][j + 1][k + 1] = max(dp[i][j + 1][k + 1], dp[i][j][k] + value)
      # 次のマスにアイテムがない/取らない場合
      for k in range(4):
        dp[i][j + 1][k] = max(dp[i][j + 1][k], dp[i][j][k])

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

Submission status: Time Limit Exceeded

Solution code:
from functools import lru_cache
import sys

sys.setrecursionlimit(100000)

n,m,k = [int(x) for x in input().split()]
v = []

@lru_cache(maxsize=4000000)
def solve(x, y, cnt):
  if x==n-1 and y == m-1:
    return 0
  
  ans = -1

  if y+1 < m:
    if cnt < 3 and v[x][y+1] != -1:
      ans = max(ans, solve(x, y + 1, cnt + 1) + v[x][y + 1])
    ans = max(ans, solve(x, y + 1, cnt))
  
  if x+1 < n:
    if v[x+1][y] != -1:
      ans = max(ans, solve(x + 1, y, 1) + v[x + 1][y])
    
    ans = max(ans, solve(x + 1, y, 0))
  
  return ans

for i in range(n):
  v.append([-1]*m)

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

ans = solve(0,0,0)

if v[0][0] != -1:
  ans = max(ans, solve(0,0,1) + v[0][0])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from functools import lru_cache
import sys

sys.setrecursionlimit(4000000)

n,m,k = [int(x) for x in input().split()]
v = []

@lru_cache(maxsize=4000000)
def solve(x, y, cnt):
  if x==n-1 and y == m-1:
    return 0
  
  ans = -1

  if y+1 < m:
    if cnt < 3 and v[x][y+1] != -1:
      ans = max(ans, solve(x, y + 1, cnt + 1) + v[x][y + 1])
    ans = max(ans, solve(x, y + 1, cnt))
  
  if x+1 < n:
    if v[x+1][y] != -1:
      ans = max(ans, solve(x + 1, y, 1) + v[x + 1][y])
    
    ans = max(ans, solve(x + 1, y, 0))
  
  return ans

for i in range(n):
  v.append([-1]*m)

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

ans = solve(0,0,0)

if v[0][0] != -1:
  ans = max(ans, solve(0,0,1) + v[0][0])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from heapq import heappush, heappop, heapify

import itertools
import math, fractions
import sys, copy

def L(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline().rstrip())
def SL(): return list(sys.stdin.readline().rstrip())
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def LIR1(n): return [LI1() for _ in range(n)]
def SR(n): return [SL() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
def LR(n): return [L() for _ in range(n)]

def perm(n, r): return math.factorial(n) // math.factorial(r)
def comb(n, r): return math.factorial(n) // math.factorial(r) // math.factorial(n-r)

def make_list(n, *args, default=0): return [make_list(*args, default=default) for _ in range(n)] if len(args) > 0 else [default for _ in range(n)]

alphabets = "abcdefghijklmnopqrstuvwxyz"
ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

sys.setrecursionlimit(1000000)
dire = [[1, 0], [0, 1], [-1, 0], [0, -1]]
dire8 = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
MOD = 1000000007
INF = float("inf")

def main():
    R, C, K = LI()
    rcv = LIR1(K)

    dp = make_list(R+1, C+1, 4)
    table = make_list(R, C)

    for r, c, v in rcv: table[r][c] = v + 1

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

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


if __name__ == '__main__':
    main()