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

Solution (Python):
import sys

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

dp = [[[0] * (C + 1) for _ in range(R + 1)] for _ in range(4)]
for i in range(R + 1):
    for j in range(C + 1):
        for k in range(4):
            here = dp[k][i][j]
            if i + 1 <= R:
                dp[0][i + 1][j] = max(dp[0][i + 1][j], here)
                dp[1][i + 1][j] = max(dp[1][i + 1][j], here + item[i + 1][j])
            if j + 1 <= C:
                dp[k][i][j + 1] = max(dp[k][i][j + 1], here)
                if k < 3:
                    dp[k + 1][i][j + 1] = max(dp[k + 1][i][j + 1], here + item[i][j + 1])
ans = 0
for k in range(4):
    ans = max(ans, dp[k][-1][-1])
print(ans)

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

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

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

for h in range(R+1):
    for w in range(C+1):
        for k in range(4):
            position = dp[k][h][w]
            if h+1 <= R:
                
                dp[0][h+1][w] = max(dp[0][h+1][w], position)
                 
                dp[1][h+1][w] = max(dp[1][h+1][w], position+item[h+1][w])
            if w+1 <= C:
                
                dp[k][h][w+1] = max(dp[k][h][w+1], position)
                
                if k < 3:
                    dp[k+1][h][w+1] = max(dp[k+1][h][w+1], position+item[h][w+1])

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

print(ans)

Solution (Python):
import sys
import numpy as np
from numba import njit, void, i8

def main():
    R, C, K = map(int, readline().split())
    items = np.array(read().split(), dtype=np.int64)
    print(calc(R, C, K, items))

@njit(i8(i8, i8, i8, i8[:]), cache=True)
def calc(R, C, K, items):
    cell = np.zeros((R, C), dtype=np.int64)
    for i in range(0, K*3, 3):
        x, y, c = items[i:i+3]
        cell[x-1, y-1] = c
    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    dp[0, 1, 0] = dp[1, 0, 0] = 0
    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, k], dp[i, j-1, k])
                if k > 0:
                    dp[i, j, k] = max(dp[i, j, k], dp[i, j, k-1])
                    dp[i, j, k] = max(dp[i, j, k], dp[i, j-1, k-1] + cell[i-1, j-1])
                if k == 1:
                    dp[i, j, 1] = max(dp[i, j, 1], dp[i-1, j, 3] + cell[i-1, j-1])
    return dp[R, C, 3]

if __name__ == "__main__":
    read = sys.stdin.buffer.read
    readline = sys.stdin.buffer.readline

    if __file__=="test.py":
        f = open("./in_out/input.txt", "r", encoding="utf-8")
        read = f.read
        readline = f.readline

    main()

Solution (Python):


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

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

    for i in range(1,R+1):
        for j in range(1,C+1):
            V = S[i][j]
            for k in range(4):
                dp[0][i][j] = max(dp[0][i][j], dp[k][i-1][j])
                dp[1][i][j] = max(dp[1][i][j], dp[k][i-1][j] + V)
                dp[k][i][j] = max(dp[k][i][j], dp[k][i][j-1])
                if k > 0:
                    dp[k][i][j] = max(dp[k][i][j], dp[k-1][i][j-1] + V)
    ans = 0
    for k in range(4):
        ans = max(ans, dp[k][R][C])
    print(ans)

if __name__ == "__main__":
    main()

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



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  

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

上からの遷移 
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


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


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]
    
    


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)  

        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],
          ))

Solution (Python):
import sys
import numpy as np
from numba import njit, void, i8
input = sys.stdin.buffer.readline

def main():
    R, C, K = map(int, input().split())
    cell = np.full((R+1, C+1), 0, dtype=np.int64)
    for i in range(K):
        x, y, c = map(int, input().split())
        cell[x-1, y-1] = c
    print(calc(cell, R, C))

@njit(i8(i8[:,:],i8,i8))
def calc(cell, R, C):
    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    dp[0, 1, 0] = dp[1, 0, 0] = 0
    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, k], dp[i, j-1, k])
                if k > 0:
                    dp[i, j, k] = max(dp[i, j, k], dp[i, j, k-1])
                    dp[i, j, k] = max(dp[i, j, k], dp[i, j-1, k-1] + cell[i-1, j-1])
                if k == 1:
                    dp[i, j, 1] = max(dp[i, j, 1], dp[i-1, j, 3] + cell[i-1, j-1])
    return dp[R, C, 3]

if __name__ == "__main__":
    main()

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



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  

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

上からの遷移 
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


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


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)  

        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],
          ))

Solution (Python):
import sys
import numpy as np
from numba import njit, void, i8
input = sys.stdin.buffer.readline

def main():
    R, C, K = map(int, input().split())
    cell = np.full((R+1, C+1), 0, dtype=np.int64)
    for i in range(K):
        x, y, c = map(int, input().split())
        cell[x-1, y-1] = c
    print(calc(cell, R, C))

@njit(i8(i8[:,:],i8,i8))
def calc(cell, R, C):
    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    dp[0, 1, 0] = dp[1, 0, 0] = 0
    for i in range(1, R + 1):
        for j in range(1, C + 1):
            for k in range(4):
                if k > 0:
                    dp[i, j, k] = max(dp[i, j, k], dp[i, j, k-1])
                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], dp[i, j-1, k-1] + cell[i-1, j-1])
                if k == 1:
                    dp[i, j, k] = max(dp[i, j, 1], dp[i-1, j, 3] + cell[i-1, j-1])
    return dp[R, C, 3]

if __name__ == "__main__":
    main()

Solution (Python):
R, C, K = map(int, input().split())
T = [[0]*(C+2) for _ in range(R+2)]
dp = [[[0]*(C+2) for _ in range(R+2)] for _ in range(4)]
for i in range(K):
    r, c, v = map(int, input().split())
    T[r][c] = v
dp[1][1][1] = T[1][1]
dp[0][1][1] = 0

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

Solution (Python):
import sys
input = sys.stdin.readline
H, W, K = map(int, input().split())
mat = [[0]*W for i in range(H)]

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

dp0 = [[-1 for i in range(W)] for i in range(H)]
dp1 = [[-1 for i in range(W)] for i in range(H)]
dp2 = [[-1 for i in range(W)] for i in range(H)]
dp3 = [[-1 for i in range(W)] for i in range(H)]

dp0[0][0] = 0
if mat[0][0] != 0:
    dp1[0][0] = mat[0][0]

for i in range(H):
    for j in range(W):
        m = max(dp0[i][j], dp1[i][j], dp2[i][j], dp3[i][j])
        if i+1 < H:
            dp1[i+1][j] = max(dp1[i+1][j], m+mat[i+1][j])
            dp0[i+1][j] = max(dp0[i+1][j], m)
        if j+1 < W:
            dp0[i][j+1] = 0
            dp1[i][j+1] = max(dp1[i][j+1], dp1[i][j], dp0[i][j]+mat[i][j+1])
            dp2[i][j+1] = max(dp2[i][j+1], dp2[i][j], dp1[i][j]+mat[i][j+1])
            dp3[i][j+1] = max(dp3[i][j+1], dp3[i][j], dp2[i][j]+mat[i][j+1])

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

Solution (Python):
import sys
import numpy as np
from numba import njit, void, i8
input = sys.stdin.buffer.readline

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

    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    cell = np.full((R+1, C+1), 0, dtype=np.int64)

    for i in range(K):
        x, y, c = map(int, input().split())
        cell[x-1, y-1] = c

    f(dp, cell, R, C)

    print(dp[R, C, 3])

@njit(void(i8[:,:,:],i8[:,:],i8,i8))
def f(dp, cell, R, C):
    dp[0, 1, 0] = dp[1, 0, 0] = 0
    for i in range(1, R + 1):
        for j in range(1, C + 1):
            for k in range(4):
                if k > 0:
                    dp[i, j, k] = max(dp[i, j, k], dp[i, j, k-1])
                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], dp[i, j-1, k-1] + cell[i-1, j-1])
                if k == 1:
                    dp[i, j, k] = max(dp[i, j, 1], dp[i-1, j, 3] + cell[i-1, j-1])

if __name__ == "__main__":
    main()

Solution (Python):
import sys,collections as cl,bisect as bs,heapq as hq
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): 
    return list(map(int,input().split()))
def m(): 
    return map(int,input().split())
def onem(): 
    return int(input())
def s(x): 
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): 
    return " ".join(map(str,x))
def max2(x): 
    return max(map(max,x))
def In(x,a): 
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

def pow_k(x, n):
    ans = 1
    while n:
        if n % 2:
            ans *= x
        x *= x
        n >>= 1
    return ans

"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

r,c,k = m()


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



for i in range(k):
    R,C,V = m()
    item[R-1][C-1] = V


dp = [[0 for k in range(4)] for j in range(c)]
dpo = [[0 for k in range(4)] for j in range(c)]
for i in range(r):
    for j in range(c):
        if j == 0:
            if item[i][j] != 0:
                po = 0
                for kk in range(4):
                    po = max(po,dpo[j][kk])
                for k in range(4):
                    if k == 0:
                        dp[j][k] = po
                    elif k == 1:
                        dp[j][k] = po + item[i][j]
                    else:
                        dp[j][k] = 0

            else:
                po = 0
                for kk in range(4):
                    po = max(po,dpo[j][kk])
                for k in range(4):
                    if k == 0:
                        dp[j][k] = po
                    else:
                        dp[j][k] = 0

        else:
            if item[i][j] != 0:
                po = 0
                for kk in range(4):
                    po = max(po,dpo[j][kk])
                for k in range(4):
                    if k == 0:
                        dp[j][k] = max(dp[j-1][k],po)
                    elif k == 1:
                        dp[j][k] = max(dp[j-1][k],dp[j-1][0] + item[i][j],po + item[i][j])
                    else:
                        dp[j][k] = max(dp[j-1][k],dp[j-1][k-1] + item[i][j])

            else:
                po = 0
                for kk in range(4):
                    po = max(po,dpo[j][kk])
                for k in range(4):
                    if k == 0:
                        dp[j][k] = max(dp[j-1][k],po)
                    else:
                        dp[j][k] = dp[j-1][k]
    for j in range(c):
        for k in range(4):
            dpo[j][k] = dp[j][k]
            dp[j][k] = 0


ans = 0

for i in range(4):
    ans = max(ans,dpo[-1][i])
print(ans)

Solution (Python):
import sys
import numpy as np
from numba import njit, void, i8
input = sys.stdin.buffer.readline

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

    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    cell = np.full((R+1, C+1), 0, dtype=np.int64)

    for i in range(K):
        x, y, c = map(int, input().split())
        cell[x-1][y-1] = c

    f(dp, cell, R, C)

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

@njit(void(i8[:,:,:],i8[:,:],i8,i8))
def f(dp, cell, R, C):
    dp[0][1][0] = dp[1][0][0] = 0
    for i in range(1, R + 1):
        for j in range(1, C + 1):
            for k in range(4):
                if k > 0:
                    dp[i][j][k] = max(dp[i][j][k], dp[i][j][k-1])
                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], dp[i][j-1][k-1] + cell[i-1][j-1])
                if k == 1:
                    dp[i][j][k] = max(dp[i][j][1], dp[i-1][j][3] + cell[i-1][j-1])

if __name__ == "__main__":
    main()

Solution (Python):
import sys
import numpy as np
from numba import njit, void, i8
input = sys.stdin.readline

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

    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    cell = np.full((R+1, C+1), 0, dtype=np.int64)

    for i in range(K):
        x, y, c = map(int, input().split())
        cell[x-1][y-1] = c

    f(dp, cell, R, C)

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

@njit(void(i8[:,:,:],i8[:,:],i8,i8))
def f(dp, cell, R, C):
    dp[0][1][0] = dp[1][0][0] = 0
    for i in range(1, R + 1):
        for j in range(1, C + 1):
            for k in range(4):
                if k > 0:
                    dp[i][j][k] = max(dp[i][j][k], dp[i][j][k-1])
                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], dp[i][j-1][k-1] + cell[i-1][j-1])
                if k == 1:
                    dp[i][j][k] = max(dp[i][j][1], dp[i-1][j][3] + cell[i-1][j-1])

if __name__ == "__main__":
    main()

Solution (Python):
import sys
import numpy as np
from numba import jit, void, i8
input = sys.stdin.readline

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

    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    cell = np.full((R+1, C+1), 0, dtype=np.int64)

    for i in range(K):
        x, y, c = map(int, input().split())
        cell[x-1][y-1] = c

    f(dp, cell, R, C)

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

@jit(void(i8[:,:,:],i8[:,:],i8,i8))
def f(dp, cell, R, C):
    dp[0][1][0] = dp[1][0][0] = 0
    for i in range(1, R + 1):
        for j in range(1, C + 1):
            for k in range(4):
                if k > 0:
                    dp[i][j][k] = max(dp[i][j][k], dp[i][j][k-1])
                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], dp[i][j-1][k-1] + cell[i-1][j-1])
                if k == 1:
                    dp[i][j][k] = max(dp[i][j][1], dp[i-1][j][3] + cell[i-1][j-1])

if __name__ == "__main__":
    main()

Solution (Python):
R, C, K, *RCV = [int(_) for _ in open(0).read().split()]
RCV = sorted([(r, -c, v) for r, c, v in zip(RCV[::3], RCV[1::3], RCV[2::3])])


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_right(self, p, v):  
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(dat[p], v)
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_left(self, p, v):  
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(v, dat[p])
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        vl = vr = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                vl = f(vl, dat[l])
                l += 1
            if r & 1:
                r -= 1
                vr = f(dat[r], vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


dp1 = SegmentTree([0] * (C + 1), max, -1)
dp2 = SegmentTree([0] * (C + 1), max, -1)
dp3 = SegmentTree([0] * (C + 1), max, -1)

rnow = 0
rcv = {}
for r, c, v in RCV:
    if rnow != r:
        rnow = r
        rcv[r] = []
    rcv[r] += [(-c, v)]
for r in sorted(rcv.keys()):
    cv = rcv[r]
    for c, v in cv:
        dp1.update(c, dp3.query(0, c + 1) + v)
    for c, v in cv:
        dp2.update(c, max(dp1.query(c, c + 1), dp1.query(0, c) + v))
    for c, v in cv:
        dp3.update(c, max(dp2.query(c, c + 1), dp2.query(0, c) + v))
ans = dp3.query(0, C + 1)
print(ans)

Solution (Python):
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 for _ in range(C+2)] for _ in range(R+2)] for _ in range(4)]

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

                if i == 3:
                    
                    dp[0][r + 1][c] = max(now, dp[0][r + 1][c])
                    continue

                
                dp[0][r+1][c] = max(now + val, dp[0][r+1][c])
                
                dp[0][r+1][c] = max(now, dp[0][r+1][c])
                
                dp[i+1][r][c+1] = max(now + val, dp[i+1][r][c+1])
                
                dp[i][r][c+1] = max(now, dp[i][r][c+1])

    print(max(dp[0][R][C], dp[1][R][C], dp[2][R][C], dp[3][R][C]))


if __name__ == "__main__":
    main()

Solution (Python):
R, C, K = map(int, input().split())
points_dict = dict()
for _ in range(K):
    r, c, v = map(int, input().split())
    points_dict[r * 30000 + c] = v

dp = [[[0] * (C+1) for _ in range(R+1)] for _ in range(4)] 
index = 0
for i in range(1, R+1):
    for j in range(1, C+1):
        
        for k in range(4):
            if dp[0][i][j] < dp[k][i-1][j]:
                dp[0][i][j] = dp[k][i-1][j]
            if dp[k][i][j] < dp[k][i][j-1]:
                dp[k][i][j] = dp[k][i][j-1]
        
        if i * 30000 + j in points_dict:
            v = points_dict[i * 30000 + j]
            for k in range(3, 0, -1):
                if dp[k][i][j] < dp[k-1][i][j] + v:
                    dp[k][i][j] = dp[k-1][i][j] + v
"""
for i in range(4):
    print(i)
    print(*dp[i], sep = '\n')
"""
print(max((dp[i][R][C] for i in range(4))))

Solution (Python):
r,c,k = map(int,input().split())
t = [[0 for i in range(c)] for i in range(r)]
for i in range(k):
    a,b,z = map(int,input().split())
    t[a-1][b-1] = z
dp = [[[0 for i in range(c)]for i in range(r)]for i in range(4)]
dp[0][0][0] = 0
dp[1][0][0] = t[0][0]
dp[2][0][0] = t[0][0]
dp[3][0][0] = t[0][0]
for i in range(r-1):
    dp[0][i+1][0] = dp[1][i][0]
    for j in range(1,4):
        dp[j][i+1][0] = dp[1][i][0]+t[i+1][0]
for i in range(c-1):
    dp[0][0][i+1] = 0
    for j in range(1,4):
        dp[j][0][i+1] = max(dp[1][0][i],t[0][i+1])
    for j in range(2,4):
        dp[j][0][i+1] = max(dp[2][0][i],dp[1][0][i]+t[0][i+1])
    dp[3][0][i+1] = max(dp[3][0][i],dp[2][0][i]+t[0][i+1])
for i in range(r-1):
    for j in range(c-1):
        u = max(dp[0][i+1][j],dp[3][i][j+1])
        for s in range(0,4):
            dp[s][i+1][j+1] =  u
        u = max(dp[0][i+1][j]+t[i+1][j+1],dp[1][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
        for s in range(1,4):
            dp[s][i+1][j+1] = u
        u = max(dp[1][i+1][j]+t[i+1][j+1],dp[2][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
        for s in range(2,4):
            dp[s][i+1][j+1] = u
        dp[3][i+1][j+1] = max(dp[2][i+1][j]+t[i+1][j+1],dp[3][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
print(dp[3][r-1][c-1])

Solution (Python):
def run():
    
    import sys
    input = sys.stdin.readline
    r,c,k = map(int,input().split())
    t = [[0 for i in range(c)] for i in range(r)]
    for i in range(k):
        a,b,z = map(int,input().split())
        t[a-1][b-1] = z
    t = tuple(t)
    dp = [[[0 for i in range(c)]for i in range(r)]for i in range(4)]
    dp[0][0][0] = 0
    dp[1][0][0] = t[0][0]
    dp[2][0][0] = t[0][0]
    dp[3][0][0] = t[0][0]
    for i in range(r-1):
        dp[0][i+1][0] = dp[1][i][0]
        for j in range(1,4):
            dp[j][i+1][0] = dp[1][i][0]+t[i+1][0]
    for i in range(c-1):
        dp[0][0][i+1] = 0
        for j in range(1,4):
            dp[j][0][i+1] = max(dp[1][0][i],t[0][i+1])
        for j in range(2,4):
            dp[j][0][i+1] = max(dp[2][0][i],dp[1][0][i]+t[0][i+1])
        dp[3][0][i+1] = max(dp[3][0][i],dp[2][0][i]+t[0][i+1])
    for i in range(r-1):
        for j in range(c-1):
            u = max(dp[0][i+1][j],dp[3][i][j+1])
            for s in range(0,4):
                dp[s][i+1][j+1] =  u
            u = max(dp[0][i+1][j]+t[i+1][j+1],dp[1][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
            for s in range(1,4):
                dp[s][i+1][j+1] = u
            u = max(dp[1][i+1][j]+t[i+1][j+1],dp[2][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
            for s in range(2,4):
                dp[s][i+1][j+1] = u
            dp[3][i+1][j+1] = max(dp[2][i+1][j]+t[i+1][j+1],dp[3][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
    print(dp[3][r-1][c-1])

if __name__ == "__main__":
    run()

Solution (Python):
import sys
input=sys.stdin.readline
H,W,K=map(int,input().split())
G=[[0]*W for i in range(H)]

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


dp0=[[-1 for i in range(W)] for i in range(H)]
dp1=[[-1 for i in range(W)] for i in range(H)]
dp2=[[-1 for i in range(W)] for i in range(H)]
dp3=[[-1 for i in range(W)] for i in range(H)]

dp0[0][0]=0
if G[0][0]!=0:
    dp1[0][0]=G[0][0]

for i in range(H):
    for j in range(W):
        m=max(dp0[i][j],dp1[i][j],dp2[i][j],dp3[i][j])
        if i+1<H:
            dp1[i+1][j]=max(dp1[i+1][j],m+G[i+1][j])
            dp0[i+1][j]=max(dp0[i+1][j],m)
        if j+1<W:
                dp0[i][j+1]=0
                dp1[i][j+1]=max(dp1[i][j+1],dp1[i][j],dp0[i][j]+G[i][j+1])
                dp2[i][j+1]=max(dp2[i][j+1],dp2[i][j],dp1[i][j]+G[i][j+1])
                dp3[i][j+1]=max(dp3[i][j+1],dp3[i][j],dp2[i][j]+G[i][j+1])
print(max(dp0[H-1][W-1],dp1[H-1][W-1],dp2[H-1][W-1],dp3[H-1][W-1]))

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

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

    for r in range(R+1):
        for c in range(C+1):
            now0 = dp0[r][c]
            now1 = dp1[r][c]
            now2 = dp2[r][c]
            now3 = dp3[r][c]
            try:
                val = grid[r][c]
            except:
                val = 0

            dp0[r+1][c] = max(now3, dp0[r+1][c])

            
            dp0[r+1][c] = max(now0 + val, now1 + val, now2 + val, dp0[r+1][c])
            
            dp0[r+1][c] = max(now0, now1, now2, now3, dp0[r+1][c])
            
            dp1[r][c+1] = max(now0 + val, dp1[r][c+1])
            dp2[r][c+1] = max(now1 + val, dp2[r][c+1])
            dp3[r][c+1] = max(now2 + val, dp3[r][c+1])

            
            dp1[r][c+1] = max(now1, dp1[r][c+1])
            dp2[r][c+1] = max(now2, dp2[r][c+1])
            dp0[r][c+1] = max(now0, dp0[r][c+1])

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


if __name__ == "__main__":
    main()