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: Wrong Answer

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

dp0 = [[0]*C for _ in range(R)]
dp1 = [[0]*C for _ in range(R)]
dp2 = [[0]*C for _ in range(R)]
dp3 = [[0]*C for _ in range(R)]

for i in range(R):
  for j in range(C):
    if j>0:
      if dp0[i][j] < dp0[i][j-1]:
        dp0[i][j] = dp0[i][j-1]
      if dp1[i][j] < dp1[i][j-1]:
        dp1[i][j] = dp1[i][j-1]
      if dp2[i][j] < dp2[i][j-1]:
        dp2[i][j] = dp2[i][j-1]
      if dp3[i][j] < dp3[i][j-1]:
        dp3[i][j] = dp3[i][j-1]
    if i>0:
      if dp0[i][j] < dp0[i-1][j]:
        dp0[i][j] = dp0[i-1][j]
      if dp0[i][j] < dp1[i-1][j]:
        dp0[i][j] = dp1[i-1][j]
      if dp0[i][j] < dp2[i-1][j]:
        dp0[i][j] = dp2[i-1][j]
      if dp0[i][j] < dp3[i-1][j]:
        dp0[i][j] = dp3[i-1][j]
    if dp1[i][j] < dp0[i][j]+board[i][j]:
      dp1[i][j] = dp0[i][j]+board[i][j]
    if dp2[i][j] < dp1[i][j]+board[i][j]:
      dp2[i][j] = dp1[i][j]+board[i][j]
    if dp3[i][j] < dp2[i][j]+board[i][j]:
      dp3[i][j] = dp2[i][j]+board[i][j]

print(max(dp0[-1][-1],dp1[-1][-1],dp2[-1][-1],dp3[-1][-1]))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import defaultdict


def read():
    R, C, K = map(int, input().strip().split())
    # アイテムの価値V[r][c]
    V = [defaultdict(int) for i in range(R+1)]
    for i in range(K):
        r, c, v = map(int, input().strip().split())
        V[r][c] = v
    return R, C, K, V


def solve(R, C, K, V):
    # dp[c][s]: c列目までにs個のアイテムを拾った時の、価値の最大値
    dp = [[0 for s in range(4)] for c in range(C+1)]
    # 次の行に移るときに使うキャッシュ
    tmp = [0 for c in range(C)]
    for r in range(1, R+1):
        for c in range(1, C+1):
            dp[c][0] = max(dp[c-1][0], dp[c][0])
            for s in range(1, 4):
                dp[c][s] = max(dp[c-1][s], dp[c-1][s-1] + V[r][c])
        # 次の行へ移る
        for c in range(1, C+1):
            tmp[c-1] = max(dp[c])
        # dpを初期化
        for c in range(C+1):  
            for s in range(4):
                dp[c][s] = 0
        for c in range(C):
            dp[c][0] = tmp[c]
    ans = 0
    for c in range(C):
        ans = max(ans, dp[c][0])
    return ans


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("%s" % str(outputs))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import defaultdict


def read():
    R, C, K = map(int, input().strip().split())
    # アイテムの価値V[r][c]
    V = [defaultdict(int) for i in range(R+1)]
    for i in range(K):
        r, c, v = map(int, input().strip().split())
        V[r][c] = v
    return R, C, K, V


def solve(R, C, K, V):
    # dp[c][s]: c列目までにs個のアイテムを拾った時の、価値の最大値
    dp = [[0 for s in range(4)] for c in range(C+1)]
    # 次の行に移るときに使うキャッシュ
    tmp = [0 for c in range(C)]
    for r in range(1, R+1):
        for c in range(1, C+1):
            for s in range(1, 4):
                dp[c][s] = max(dp[c-1][s], dp[c-1][s-1] + V[r][c])
        # 次の行へ移る
        for c in range(1, C+1):
            tmp[c-1] = max(dp[c])
        # dpを初期化
        for c in range(C+1):  
            for s in range(4):
                dp[c][s] = 0
        for c in range(C):
            dp[c][0] = tmp[c]
    ans = 0
    for c in range(C):
        ans = max(ans, dp[c][0])
    return ans


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("%s" % str(outputs))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import defaultdict


def read():
    R, C, K = map(int, input().strip().split())
    # アイテムの価値V[r][c]
    V = [defaultdict(int) for i in range(R+1)]
    for i in range(K):
        r, c, v = map(int, input().strip().split())
        V[r][c] = v
    return R, C, K, V


def solve(R, C, K, V):
    # dp[c][s]: c列目までにs個のアイテムを拾った時の、価値の最大値
    dp = [[0 for s in range(4)] for c in range(C+1)]
    for r in range(1, R+1):
        for c in range(1, C+1):
            for s in range(1, 4):
                dp[c][s] = max(dp[c-1][s], dp[c-1][s-1] + V[r][c])
        # 次の行へ移る
        for c in range(1, C+1):
            dp[c-1][0] = max(dp[c])
    ans = 0
    for c in range(C):
        ans = max(ans, dp[c][0])
    return ans


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("%s" % str(outputs))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def exit(*argv, **kwarg):
    print(*argv, **kwarg)
    sys.exit()


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def a_int(): return int(read())


def ints(): return list(map(int, read().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque


'''
dp[i][j]...(0,0)からスタートして(i,j)に到達する経路のなかでの最大の価値
dp[i][j]=max(dp[i][j-1],dp[i-1][j]) + v[i][j]


dp[i][j][k] ... (0,0)からスタートして(i,j)に到達する経路のなかでi行目ですでにk(以下)個選んでいるときの最大の価値

遷移は、i,jのvを拾うときと拾わないときのmax
dp[i][j][k] = max(dp[i][j-1][k-1]+V[i,j], dp[i][j-1][k]
                  ) #k個のままのほうが価値が高いかk-1から拾ったほうが価値が高いか

上からの遷移 # 拾うか拾わないかでこうかな
dp[i][j][0]=max(dp[i][j-1][0],max_k(dp[i-1][j]))
dp[i][j][1]=max(dp[i][j-1][0],max_k(dp[i-1][j][k])+V[i][j])
'''

R, C, K = ints()
RCV = read_tuple(K)
V = [[0] * C for _ in ra(R)]
for r, c, v in RCV:
    V[r - 1][c - 1] = v

# dp = [[[0] * 4 for _ in ra(C)] for _ in ra(R)]
dp0 = [[0] * C for _ in ra(R)]
dp1 = [[0] * C for _ in ra(R)]
dp2 = [[0] * C for _ in ra(R)]
dp3 = [[0] * C for _ in ra(R)]

# dp[0][0][0] = 0
dp1[0][0] = V[0][0]
dp2[0][0] = V[0][0]
dp3[0][0] = V[0][0]

for j in ra(1, C):
    dp1[0][j] = max(dp1[0][j - 1], dp0[0][j - 1] + V[0][j])
    dp2[0][j] = max(dp2[0][j - 1], dp1[0][j - 1] + V[0][j])
    dp3[0][j] = max(dp3[0][j - 1], dp2[0][j - 1] + V[0][j])

for i in ra(1, R):
    dp0[i][0] = dp1[i - 1][0]
    dp1[i][0] = dp0[i][0] + V[i][0]
    dp2[i][0] = dp0[i][0] + V[i][0]
    dp3[i][0] = dp0[i][0] + V[i][0]


for i in ra(1, R):
    for j in ra(1, C):
        ma = max(dp0[i - 1][j],
                 dp1[i - 1][j],
                 dp2[i - 1][j],
                 dp3[i - 1][j])

        dp0[i][j] = max(dp0[i][j - 1],  # 左
                        ma)  # 上

        if ma > max(dp3[i][j - 1], dp2[i][j - 1], dp1[i][j - 1]):  # 上から採用
            dp1[i][j] = ma + V[i][j]
            dp2[i][j] = ma + V[i][j]
            dp3[i][j] = ma + V[i][j]
        else:  # 横から採用
            dp1[i][j] = max(dp0[i][j - 1] + V[i][j],  # 左から来て拾う
                            dp1[i][j - 1])  # 拾わないほうが大きい場合もある
            dp2[i][j] = max(dp1[i][j - 1] + V[i][j], dp2[i][j - 1])
            dp3[i][j] = max(dp2[i][j - 1] + V[i][j], dp3[i][j - 1])


print(max(dp0[R - 1][C - 1],
          dp1[R - 1][C - 1],
          dp2[R - 1][C - 1],
          dp3[R - 1][C - 1],
          ))

# print(*values, sep='\n')
# print(*dp3, sep='\n')

# dp2 = [[-1] * C for _ in ra(R)]
# for i in ra(R):
#     for j in ra(C):
#         dp2[i][j] = max(dp[i][j])
# print(*dp2, sep='\n')

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

R,C,K = LI()
r,c,v = LIR(K,3)

a = [[0]*C for _ in range(R)]
for i in range(K):
    a[r[i]-1][c[i]-1] = v[i]

#dp = [[[0]*4 for _ in range(C)] for _ in range(R)]
#if a[0][0]:
#    dp[0][0][1] = a[0][0]

dp = [0]*(4*C*R)

"""
for i in range(R):
    for j in range(C):
        upper_max = max(dp[i-1][j]) if i >= 1 else 0
        for k in range(4):
            dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k])
            if k == 0:
                dp[i][j][k] = max(dp[i][j][k],upper_max)
            if a[i][j] != 0:
                if k == 1 and i >= 1:
                    dp[i][j][k] = max(dp[i][j][k],upper_max+a[i][j])
                if k >= 1 and j >= 1:
                    dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k-1]+a[i][j])

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

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def exit(*argv, **kwarg):
    print(*argv, **kwarg)
    sys.exit()


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def a_int(): return int(read())


def ints(): return list(map(int, read().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque


'''
dp[i][j]...(0,0)からスタートして(i,j)に到達する経路のなかでの最大の価値
dp[i][j]=max(dp[i][j-1],dp[i-1][j]) + v[i][j]


dp[i][j][k] ... (0,0)からスタートして(i,j)に到達する経路のなかでi行目ですでにk(以下)個選んでいるときの最大の価値

遷移は、i,jのvを拾うときと拾わないときのmax
dp[i][j][k] = max(dp[i][j-1][k-1]+V[i,j], dp[i][j-1][k]
                  ) #k個のままのほうが価値が高いかk-1から拾ったほうが価値が高いか

上からの遷移 # 拾うか拾わないかでこうかな
dp[i][j][0]=max(dp[i][j-1][0],max_k(dp[i-1][j]))
dp[i][j][1]=max(dp[i][j-1][0],max_k(dp[i-1][j][k])+V[i][j])
'''

R, C, K = ints()
RCV = read_tuple(K)
V = [[0] * C for _ in ra(R)]
for r, c, v in RCV:
    V[r - 1][c - 1] = v

# dp = [[[0] * 4 for _ in ra(C)] for _ in ra(R)]
dp0 = [[0] * C for _ in ra(R)]
dp1 = [[0] * C for _ in ra(R)]
dp2 = [[0] * C for _ in ra(R)]
dp3 = [[0] * C for _ in ra(R)]

# dp[0][0][0] = 0
dp1[0][0] = V[0][0]
dp2[0][0] = V[0][0]
dp3[0][0] = V[0][0]

for j in ra(1, C):
    dp1[0][j] = max(dp1[0][j - 1], dp0[0][j - 1] + V[0][j])
    dp2[0][j] = max(dp2[0][j - 1], dp1[0][j - 1] + V[0][j])
    dp3[0][j] = max(dp3[0][j - 1], dp2[0][j - 1] + V[0][j])

for i in ra(1, R):
    dp0[i][0] = dp1[i - 1][0]
    dp1[i][0] = dp0[i][0] + V[i][0]
    # dp2[i][0] = dp0[i][0] + V[i][0]
    # dp3[i][0] = dp0[i][0] + V[i][0]


for i in ra(1, R):
    for j in ra(1, C):
        ma = max(dp0[i - 1][j],
                 dp1[i - 1][j],
                 dp2[i - 1][j],
                 dp3[i - 1][j])

        dp0[i][j] = max(dp0[i][j - 1],  # 左
                        ma)  # 上

        # if ma + V[i][j] > ma(dp3[i][j]):

        dp1[i][j] = max(dp0[i][j - 1] + V[i][j],  # 左から来て拾う
                        # dp1[i][j - 1],  # 拾わないほうが大きい場合もある
                        ma + V[i][j])  # 上から来て拾う

        dp2[i][j] = max(dp1[i][j - 1] + V[i][j], dp2[i][j - 1])
        dp3[i][j] = max(dp2[i][j - 1] + V[i][j], dp3[i][j - 1])


print(max(dp0[R - 1][C - 1],
          dp1[R - 1][C - 1],
          dp2[R - 1][C - 1],
          dp3[R - 1][C - 1],
          ))

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

# dp2 = [[-1] * C for _ in ra(R)]
# for i in ra(R):
#     for j in ra(C):
#         dp2[i][j] = max(dp[i][j])
# print(*dp2, sep='\n')

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

R,C,K = LI()
r,c,v = LIR(K,3)

a = [[0]*C for _ in range(R)]
for i in range(K):
    a[r[i]-1][c[i]-1] = v[i]

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

"""
for i in range(R):
    for j in range(C):
        upper_max = max(dp[i-1][j]) if i >= 1 else 0
        for k in range(4):
            dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k])
            if k == 0:
                dp[i][j][k] = max(dp[i][j][k],upper_max)
            if a[i][j] != 0:
                if k == 1 and i >= 1:
                    dp[i][j][k] = max(dp[i][j][k],upper_max+a[i][j])
                if k >= 1 and j >= 1:
                    dp[i][j][k] = max(dp[i][j][k],dp[i][j-1][k-1]+a[i][j])

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

Submission status: Wrong Answer

Solution code:
import numpy as np
from numba import njit, types
from numba.typed import Dict


@njit
def solve(R, C, items):
    dp = np.zeros((R + 1, C + 1, 4), dtype=np.int64)
    for i in range(1, R + 1):
        for j in range(1, C + 1):
            for k in range(4):
                dp[i][j][k] = max(dp[i][j - 1][k], dp[i - 1][j][3])
            if R * i + j not in items:
                continue
            for k in range(3, 0, -1):
                dp[i][j][k] = max(dp[i][j][k], dp[i][j][k - 1] + items[R * i + j])
    return dp[R][C][3]


R, C, K, *rcv = map(int, open(0).read().split())

items = Dict.empty(key_type=types.int64, value_type=types.int64)
for r, c, v in zip(*[iter(rcv)] * 3):
    items[R * r + c] = v

print(solve(R, C, items))

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
input = sys.stdin.readline


def main():
    h, w, k = map(int, input().split())
    values = np.zeros((h, w), dtype=np.int64)
    items = np.array([list(map(int, input().split())) for _ in range(k)])
    ys, xs, vs = items[:, 0] - 1, items[:, 1] - 1, items[:, 2]
    values[ys, xs] = vs

    DP = np.zeros(w+1, dtype=np.int64)
    for line in values:
        for _ in range(3):
            DP[1:] = np.maximum(DP[:-1] + line, DP[1:])
            DP = np.maximum.accumulate(DP)
        DP[:-1] = DP[1:]
    print(DP[-1])


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import bisect
import sys,io
import math
from collections import deque
from heapq import heappush, heappop

def sRaw():
    return input().rstrip("\r")


def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))

INF = 1 << 29

def make2d_arr(h, w, val=INF):
    return [[val for i in range(w)]for i in range(h)]

DIV = (10**9) + 7
#DIV = 998244353

def mod_inv_prime(a, mod=DIV):
    return pow(a, mod-2, mod)


def mod_inv(a, b):
    r = a
    w = b
    u = 1
    v = 0
    while w != 0:
        t = r//w
        r -= t*w
        r, w = w, r
        u -= t*v
        u, v = v, u
    return (u % b+b) % b


def CONV_TBL(max, mod=DIV):
    fac, finv, inv = [0]*max, [0]*max, [0]*max
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1
    for i in range(2, max):
        fac[i] = fac[i-1]*i % mod
        inv[i] = mod - inv[mod % i] * (mod//i) % mod
        finv[i] = finv[i-1]*inv[i] % mod

    class CONV:
        def __init__(self):
            self.fac = fac
            self.finv = finv
            pass

        def ncr(self, n, k):
            if(n < k):
                return 0
            if(n < 0 or k < 0):
                return 0
            return fac[n]*(finv[k]*finv[n-k] % DIV) % DIV

    return CONV()


def cumsum(As):
    s = 0
    for a in As:
        s += a
        yield s


sys.setrecursionlimit(200005)


def dijkstra(G,start=0):
    heap = []
    cost = [INF]*len(G)
    heappush(heap,(0,start))
    while len(heap)!=0:
        c,n = heappop(heap)
        if cost[n] !=INF:
            continue
        cost[n]=c
        for e in G[n]:
            ec,v = e
            if cost[v]!=INF:
                continue
            heappush(heap,(ec+c,v))
    return cost


def main():
    R,C,K = isRaw()
    mas = make2d_arr(R,C,0)
    for k in range(K):
        r,c,v = isRaw()
        mas[r-1][c-1]=v
    dp = [make2d_arr(C,4,0) for r in range(R)]
    dp[0][0][1]=mas[0][0]
    dp[0][0][2]=mas[0][0]
    for r in range(R):
        for c in range(C):
            if r>0:
                dp[r][c][0] = max(dp[r][c][0],dp[r-1][c][-1] )
                dp[r][c][1] = max(dp[r][c][1],dp[r-1][c][-1]+mas[r][c])
                dp[r][c][2] = max(dp[r][c][2],dp[r-1][c][-1]+mas[r][c])
                dp[r][c][3] = max(dp[r][c][3],dp[r-1][c][-1]+mas[r][c])
            if c>0:
                dp[r][c][0] = max(dp[r][c][0],dp[r][c-1][0])
                dp[r][c][1] = max(dp[r][c][1], dp[r][c-1][1], dp[r][c-1][0]+mas[r][c])
                dp[r][c][2] = max(dp[r][c][2], dp[r][c-1][2], dp[r][c-1][1]+mas[r][c])
                dp[r][c][3] = max(dp[r][c][3], dp[r][c-1][3], dp[r][c-1][2]+mas[r][c])
            

    print(max([dp[-1][-1][ni] for ni in range(4)]))

main()

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
input = sys.stdin.readline


def main():
    h, w, k = map(int, input().split())
    values = np.zeros((h, w), dtype=np.int64)
    items = np.array([list(map(int, input().split())) for _ in range(k)])
    ys, xs, vs = items[:, 0] - 1, items[:, 1] - 1, items[:, 2]
    values[ys, xs] = vs

    DP = np.zeros(w+1, dtype=np.int64)
    for line in values:
        for _ in range(3):
            DP[1:] = np.maximum(DP[:-1] + line, DP[1:])
            DP[1:] = np.maximum.accumulate(DP[1:])
        DP[:-1] = DP[1:]
    print(DP[-1])


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# by the authority of GOD     author: manhar singh sachdev #

import os,sys
from io import BytesIO, IOBase

def main():
    R,C,K = map(int,input().split())
    arr = [[0]*C for _ in range(R)]
    for _ in range(K):
        r,c,v = map(int,input().split())
        arr[r-1][c-1] = v
    dp = [[0]*C for _ in range(R)]
    for i in range(R):
        x = []
        carry = dp[i-1][0]
        for j in range(C):
            y = x[:]
            if len(y) == 3:
                if min(y) < arr[i][j]:
                    y.remove(min(y))
                    y.append(arr[i][j])
            else:
                y.append(arr[i][j])
            if i and j and dp[i-1][j]+arr[i][j] > sum(y)+carry:
                x = []
                carry = dp[i-1][j]
            if len(x) == 3:
                if min(x) < arr[i][j]:
                    x.remove(min(x))
                    x.append(arr[i][j])
            else:
                x.append(arr[i][j])
            dp[i][j] = sum(x)+carry
    print(dp[-1][-1])

#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
R,C,K = ma()
V = [[0 for i in range(R+1)] for j in range(C+1)]
for i in range(K):
    r,c,v = ma()
    V[c][r] = v
v3 = [[[0]*3 for i in range(R+1)]  for j in range(C+1)]#行のお宝3つ
dp_con = [[0 for i in range(R+1)] for j in range(C+1)] #確定した分
for c in range(1,C+1):
    for r in range(1,R+1):
        #同じ行で更新
        v3[c][r] = v3[c-1][r].copy()
        hq.heappushpop(v3[c][r], V[c][r])
        dp_con[c][r] = dp_con[c-1][r]
        #違う行からの可算との比較
        sumv1 = sum(v3[c][r-1])
        if sumv1+dp_con[c][r-1] + V[c][r] >=sum(v3[c][r])+ dp_con[c][r]:
            dp_con[c][r] = sumv1+dp_con[c][r-1]
            v3[c][r] = [0]*2 + [V[c][r]]
        else:
            pass

print(dp_con[C][R] + sum(v3[C][R]))
#print(V)
#for i in  range(1,C+1):
#    print("V",V[i])
#    print("v3",v3[i])
#    print("confirm",dp_con[i])

Submission status: Wrong Answer

Solution code:
# by the authority of GOD     author: manhar singh sachdev #

import os,sys
from io import BytesIO, IOBase

def main():
    R,C,K = map(int,input().split())
    arr = [[0]*C for _ in range(R)]
    for _ in range(K):
        r,c,v = map(int,input().split())
        arr[r-1][c-1] = v
    dp = [[0]*C for _ in range(R)]
    for i in range(R):
        x = []
        if i:
            carry = dp[i-1][0]
        else:
            carry = 0
        for j in range(C):
            if i and j and dp[i-1][j] > dp[i][j-1]:
                x = []
                carry = dp[i-1][j]
            if len(x) == 3:
                if min(x) < arr[i][j]:
                    x.remove(min(x))
                    x.append(arr[i][j])
            else:
                x.append(arr[i][j])
            dp[i][j] = sum(x)+carry
    print(dp[-1][-1])

#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

    dp = [[[0]*4 for _ in range(C+1)] for _ in range(R+1)]
    # もらうdpにしてみる
    for i in range(R):
        for j in range(C):
            # アイテム取らないorない
            for k in range(4):
                dp[i+1][j+1][0] = max(dp[i+1][j+1][0], dp[i][j+1][k])
            for k in range(4):
                dp[i+1][j+1][k] = max(dp[i+1][j+1][k], dp[i+1][j][k])
            # アイテムとる
            if S[i][j] > 0:
                for k in range(3):# アイテムは3個まで
                    dp[i+1][j+1][0] = max(dp[i+1][j+1][0], dp[i][j+1][k] + S[i][j])
                for k in range(3):
                    dp[i+1][j+1][k+1] = max(dp[i+1][j+1][k+1], dp[i+1][j][k] + S[i][j])

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

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def exit(*argv, **kwarg):
    print(*argv, **kwarg)
    sys.exit()


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def a_int(): return int(read())


def ints(): return list(map(int, read().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque


'''
dp[i][j]...(0,0)からスタートして(i,j)に到達する経路のなかでの最大の価値
dp[i][j]=max(dp[i][j-1],dp[i-1][j]) + v[i][j]


dp[i][j][k] ... (0,0)からスタートして(i,j)に到達する経路のなかでi行目ですでにk(以下)個選んでいるときの最大の価値

遷移は、i,jのvを拾うときと拾わないときのmax
dp[i][j][k] = max(dp[i][j-1][k-1]+V[i,j], dp[i][j-1][k]
                  ) #k個のままのほうが価値が高いかk-1から拾ったほうが価値が高いか

上からの遷移 # 拾うか拾わないかでこうかな
dp[i][j][0]=max(dp[i][j-1][0],max_k(dp[i-1][j]))
dp[i][j][1]=max(dp[i][j-1][0],max_k(dp[i-1][j][k])+V[i][j])
'''

R, C, K = ints()
RCV = read_tuple(K)
V = [[0] * C for _ in ra(R)]
for r, c, v in RCV:
    V[r - 1][c - 1] = v

# dp = [[[0] * 4 for _ in ra(C)] for _ in ra(R)]
dp = []
for _ in ra(R):
    tmp = []
    for _ in ra(C):
        tmp.append([0] * 4)
    dp.append(tmp)

# dp[0][0][0] = 0
for k in ra(1, 4):
    dp[0][0][k] = V[0][0]
for j in ra(1, C):
    for k in ra(1, 4):
        dp[0][j][k] = max(dp[0][j - 1][k], dp[0][j - 1][k - 1] + V[0][j])

exit(0)
for i in ra(1, R):
    dp[i][0][0] = max(dp[i - 1][0])
    dp[i][0][1] = dp[i][0][0] + V[i][0]
    dp[i][0][2] = dp[i][0][0] + V[i][0]
    dp[i][0][3] = dp[i][0][0] + V[i][0]


for i in ra(1, R):
    for j in ra(1, C):
        ma = max(dp[i - 1][j])
        dp[i][j][0] = max(dp[i][j - 1][0],  # 左
                          ma)  # 上

        dp[i][j][1] = max(dp[i][j - 1][0] + V[i][j],  # 左から来て拾う
                          dp[i][j - 1][1],  # 拾わないほうが大きい場合もある
                          ma + V[i][j])  # 上から来て拾う

        dp[i][j][2] = max(dp[i][j - 1][1] + V[i][j], dp[i][j - 1][2])
        dp[i][j][3] = max(dp[i][j - 1][2] + V[i][j], dp[i][j - 1][3])


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

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

# dp2 = [[-1] * C for _ in ra(R)]
# for i in ra(R):
#     for j in ra(C):
#         dp2[i][j] = max(dp[i][j])
# print(*dp2, sep='\n')

Submission status: Wrong Answer

Solution code:
R,C,K=map(int,input().split())
RCV=[list(map(int,input().split())) for i in range(K)]
V={}
for r,c,v in RCV:
    V[(r-1,c-1)]=v
d=[[[0]*4 for i in range(C+1)] for i in range(R+1)]
for i in range(R):
    for j in range(C):
        if (i,j) in V:
            m=max(d[i][j+1])
            d[i+1][j+1][0]=m
            d[i+1][j+1][1]=max(d[i+1][j][1],m+V[(i,j)],d[i+1][j][0]+V[(i,j)])
            d[i+1][j+1][2]=max(d[i+1][j][2],d[i+1][j][1]+V[(i,j)])
            d[i+1][j+1][3]=max(d[i+1][j][3],d[i+1][j][2]+V[(i,j)])
        else:
            d[i+1][j+1]=d[i+1][j]
print(max(d[-1][-1]))