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 bisect, copy, heapq, math, sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
def celi(a,b):
    return -(-a//b)
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

def main():
    r,c,k=map(int,input().split())
    rcv=[list(map(int,input().split())) for i in range(k)]

    dpn=[[0]*4 for i in range(c+1)]

    dic={}
    for i in range(k):
        r1,c1,v=rcv[i]
        dic[(r1,c1)]=v

    for i in range(r):
        for j in range(c):
            dpn[j+1][0]=max(dpn[j+1][0],max(dpn[j+1]))
            if (i+1,j+1) in dic:
                for k in range(3)[::-1]:
                    dpn[j+1][k+1]=max(dpn[j+1][k]+dic[(i+1,j+1)],dpn[j][k]+dic[(i+1,j+1)])
            for k in range(4):
                dpn[j+1][k]=max(dpn[j+1][k],dpn[j][k])
        
    print(max(dpn[-1]))

main()

Solution (Python):
import sys
input = sys.stdin.readline

def main():
    r,c,k = map(int, input().split())
    rcv = [ [0]*c for _ in range(r) ]

    for _ in range(k):
        ri,ci,vi = map(int, input().split())
        rcv[ri-1][ci-1] = vi

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


    dp[1][0][0] = rcv[0][0]
    for i in range(r):
        for j in range(c):
            if i+1 < r:
                dp[0][i+1][j] = max(dp[0][i][j], dp[1][i][j], dp[2][i][j], dp[3][i][j], dp[0][i+1][j])
                if rcv[i+1][j] > 0:
                    dp[1][i+1][j] = max(dp[1][i+1][j],  max(dp[0][i][j], dp[1][i][j], dp[2][i][j], dp[3][i][j])+rcv[i+1][j])

            if j+1 < c:
                dp[0][i][j+1] = max(dp[0][i][j], dp[0][i][j+1])
                dp[1][i][j+1] = max(dp[1][i][j], dp[1][i][j+1])
                dp[2][i][j+1] = max(dp[2][i][j], dp[2][i][j+1])
                dp[3][i][j+1] = max(dp[3][i][j], dp[3][i][j+1])
                if rcv[i][j+1] > 0:
                    dp[1][i][j+1] = max(dp[1][i][j+1], dp[0][i][j]+rcv[i][j+1])
                    dp[2][i][j+1] = max(dp[2][i][j+1], dp[1][i][j]+rcv[i][j+1])
                    dp[3][i][j+1] = max(dp[3][i][j+1], dp[2][i][j]+rcv[i][j+1])

    ans = max(dp[0][r-1][c-1], dp[1][r-1][c-1], dp[2][r-1][c-1], dp[3][r-1][c-1])
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import sys

inp = [int(x) for x in sys.stdin.read().split()]; ii = 0

rows, cols, k = inp[ii:ii+3]; ii += 3
items = [[] for _ in range(rows+1)]
best = [0]*(cols+1)
for _ in range(k):
	r, c, v = inp[ii:ii+3]; ii += 3
	items[r].append([c, v])
for i in range(rows+1):
	items[i].sort()
ans = 0
for r in range(1, rows+1):
	dp = []
	best1, best2 = 0, 0
	Row = items[r]
	for c, v in Row:
		v1 = best[c] + v
		v2 = best1 + v
		v3 = best2 + v
		V = v1
		if V < v2:
			V = v2
		if V < v3:
			V = v3
		dp.append(V)
		if v1 > best1:
			best1 = v1
		if v2 > best2:
			best2 = v2
		if ans < V:
			ans = V
	for j in range(len(dp)):
		if best[Row[j][0]] < dp[j]:
			best[Row[j][0]] = dp[j]
	for j in range(2, cols+1):
		if best[j] < best[j-1]:
			best[j] = best[j-1]
print(ans)

Solution (Python):
r,c,k = map(int, input().split())
rcv = [ [0]*c for _ in range(r) ]

for _ in range(k):
    ri,ci,vi = map(int, input().split())
    rcv[ri-1][ci-1] = vi





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


dp[1][0][0] = rcv[0][0]
for i in range(r):
    for j in range(c):
        if i+1 < r:
            dp[0][i+1][j] = max(dp[0][i][j], dp[1][i][j], dp[2][i][j], dp[3][i][j], dp[0][i+1][j])
            if rcv[i+1][j] > 0:
                dp[1][i+1][j] = max(dp[1][i+1][j],  max(dp[0][i][j], dp[1][i][j], dp[2][i][j], dp[3][i][j])+rcv[i+1][j])

        if j+1 < c:
            dp[0][i][j+1] = max(dp[0][i][j], dp[0][i][j+1])
            dp[1][i][j+1] = max(dp[1][i][j], dp[1][i][j+1])
            dp[2][i][j+1] = max(dp[2][i][j], dp[2][i][j+1])
            dp[3][i][j+1] = max(dp[3][i][j], dp[3][i][j+1])
            if rcv[i][j+1] > 0:
                dp[1][i][j+1] = max(dp[1][i][j+1], dp[0][i][j]+rcv[i][j+1])
                dp[2][i][j+1] = max(dp[2][i][j+1], dp[1][i][j]+rcv[i][j+1])
                dp[3][i][j+1] = max(dp[3][i][j+1], dp[2][i][j]+rcv[i][j+1])

ans = max(dp[0][r-1][c-1], dp[1][r-1][c-1], dp[2][r-1][c-1], dp[3][r-1][c-1])
print(ans)

Solution (Python):
import sys
def input():
	return sys.stdin.buffer.readline()[:-1]

n, m, q = map(int, input().split())
g = [[0 for _ in range(m)] for _ in range(n)]
for _ in range(q):
	r, c, v = list(map(int, input().split()))
	g[r-1][c-1] = v

pre = [0 for _ in range(m)]
dp = [[0 for _ in range(4)] for _ in range(m)]
dp[0][1] = g[0][0]
for i in range(n):
	for j in range(m):
		dp[j][0] = max(dp[j][0], pre[j])
		if j > 0:
			dp[j][0] = max(dp[j][0], dp[j-1][0])
			for k in range(1, 4):
				dp[j][k] = max(dp[j][k], dp[j-1][k])
				dp[j][k] = max(dp[j][k], dp[j-1][k-1] + g[i][j])
			if i > 0:
				dp[j][1] = max(dp[j][1], pre[j] + g[i][j])
		else:
			dp[0][1] = max(dp[0][1], pre[0] + g[i][j])
	pre = [max(dp[j]) for j in range(m)]
	dp = [[0 for _ in range(4)] for _ in range(m)]

print(pre[-1])

Solution (Python):
import sys


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

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

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

    
    dp = [[[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):
            for m in range(4):
                dp[m][i][j] = max(dp[3][i - 1][j], dp[m][i][j - 1])
            if items[i][j] > 0:
                for m in [2, 1, 0]:
                    dp[m + 1][i][j] = max(dp[m + 1][i][j],
                                          dp[m][i][j] + items[i][j])

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


if __name__ == '__main__':
    main()

Solution (Python):
r,c,k = map(int, input().split())
rcv = [ [0]*c for _ in range(r) ]

for _ in range(k):
    ri,ci,vi = map(int, input().split())
    rcv[ri-1][ci-1] = vi

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

dp1[0][0] = rcv[0][0]
for i in range(r):
    for j in range(c):
        if i+1 < r:
            dp0[i+1][j] = max(dp0[i][j], dp1[i][j], dp2[i][j], dp3[i][j], dp0[i+1][j])
            if rcv[i+1][j] > 0:
                dp1[i+1][j] = max(dp1[i+1][j],  max(dp0[i][j], dp1[i][j], dp2[i][j], dp3[i][j])+rcv[i+1][j])

        if j+1 < c:
            dp0[i][j+1] = max(dp0[i][j], dp0[i][j+1])
            dp1[i][j+1] = max(dp1[i][j], dp1[i][j+1])
            dp2[i][j+1] = max(dp2[i][j], dp2[i][j+1])
            dp3[i][j+1] = max(dp3[i][j], dp3[i][j+1])
            if rcv[i][j+1] > 0:
                dp1[i][j+1] = max(dp1[i][j+1], dp0[i][j]+rcv[i][j+1])
                dp2[i][j+1] = max(dp2[i][j+1], dp1[i][j]+rcv[i][j+1])
                dp3[i][j+1] = max(dp3[i][j+1], dp2[i][j]+rcv[i][j+1])

ans = max(dp0[r-1][c-1], dp1[r-1][c-1], dp2[r-1][c-1], dp3[r-1][c-1])
print(ans)

Solution (Python):
rows, cols, k = map(int, input().split())
items = [[] for _ in range(rows+1)]
best = [0]*(cols+1)
for _ in range(k):
	r, c, v = map(int, input().split())
	items[r].append([c, v])
for i in range(rows+1):
	items[i].sort()
ans = 0
for r in range(1, rows+1):
	dp = []
	best1, best2 = 0, 0
	Row = items[r]
	for c, v in Row:
		v1 = best[c] + v
		v2 = best1 + v
		v3 = best2 + v
		V = max(v1, v2, v3)
		dp.append(V)
		if v1 > best1:
			best1 = v1
		if v2 > best2:
			best2 = v2
		if ans < V:
			ans = V
	for j in range(len(dp)):
		if best[Row[j][0]] < dp[j]:
			best[Row[j][0]] = dp[j]
	for j in range(2, cols+1):
		if best[j] < best[j-1]:
			best[j] = best[j-1]
print(ans)

Solution (Python):
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    R, C, K, *RCV = map(int, read().split())

    item = [[0] * C for _ in range(R)]
    for r, c, v in zip(*[iter(RCV)] * 3):
        item[r - 1][c - 1] = v

    dp = [0] * (C + 1)
    for i in range(R):
        dp, dp_prev = [0] * (C + 1), dp
        v = [0] * 4
        for j in range(C):
            for k in range(4):
                if v[k] < dp_prev[j + 1]:
                    v[k] = dp_prev[j + 1]
                else:
                    break
            if item[i][j] > 0:
                for k in range(2, -1, -1):
                    if v[k + 1] < v[k] + item[i][j]:
                        v[k + 1] = v[k] + item[i][j]
            dp[j + 1] = v[3]

    print(dp[C])

    return


if __name__ == '__main__':
    main()

Solution (Python):


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

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

DP1 = [0 for _ in range(C+1)]
DP2 = [0 for _ in range(C+1)]
DP3 = [0 for _ in range(C+1)]
for r in range(1,R+1):
  for c in range(1,C+1):
    item = items[r][c]
    DP1[c] = max(DP3[c]+item,DP1[c-1])
    DP2[c] = max(DP1[c],DP2[c-1],DP1[c-1]+item)
    DP3[c] = max(DP2[c],DP3[c-1],DP2[c-1]+item)
        
print(DP3[C])

Solution (Python):
import sys
from collections import defaultdict
range = xrange
input = raw_input

inp = [int(x) for x in sys.stdin.read().split()]; ii = 0

n = inp[ii]; ii += 1
m = inp[ii]; ii += 1
k = inp[ii]; ii += 1

R = inp[ii + 0: ii + 3 * k: 3]
C = inp[ii + 1: ii + 3 * k: 3]
V = inp[ii + 2: ii + 3 * k: 3]

items = [defaultdict(list) for _ in range(n)]
for i in range(k):
    r = R[i] - 1
    c = C[i] - 1
    v = V[i]
    items[r][c].append(v)

DP0 = [0] * m
DP1 = [0] * m
DP2 = [0] * m
DP3 = [0] * m

for r in range(n):
    itemsr = items[r]
    for c in range(m):
        if c:
            DP0[c] = max(DP0[c], DP0[c - 1])
            DP1[c] = max(DP1[c], DP1[c - 1])
            DP2[c] = max(DP2[c], DP2[c - 1])
            DP3[c] = max(DP3[c], DP3[c - 1])
        if c in itemsr:
            for v in itemsr[c]:
                DP3[c] = max(DP3[c], DP2[c] + v)
                DP2[c] = max(DP2[c], DP1[c] + v)
                DP1[c] = max(DP1[c], DP0[c] + v)
    for c in range(m):
        DP0[c] = DP1[c] = DP2[c] = DP3[c]
print DP0[-1]

Solution (Python):
R,C,k=map(int,input().split())
rcv = [[0 for _ in range(C+1)] for _ in range(R+1)]
for i in range(k):
  r,c,v = map(int,input().split())
  rcv[r][c] = v

dp0=[[0 for _ in range(C+1)] for _ in range(R+1)]
dp1=[[0 for _ in range(C+1)] for _ in range(R+1)]
dp2=[[0 for _ in range(C+1)] for _ in range(R+1)]
dp3=[[0 for _ in range(C+1)] for _ in range(R+1)]
dp1[1][1] = rcv[1][1]
for r in range(1,R+1):
  for c in range(1,C+1):
    dp1[r][c] = max(dp0[r][c]+rcv[r][c],dp0[r][c-1]+rcv[r][c],dp1[r][c-1])
    dp2[r][c] = max(dp1[r][c-1]+rcv[r][c],dp2[r][c-1])
    dp3[r][c] = max(dp2[r][c-1]+rcv[r][c],dp3[r][c-1])
    
    if r < R:
      dp0[r+1][c] = max(dp0[r][c],dp1[r][c],dp2[r][c],dp3[r][c])
print(max(dp0[R][C],dp1[R][C],dp2[R][C],dp3[R][C]))

Solution (Python):
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    R, C, K, *RCV = map(int, read().split())

    item = [[0] * C for _ in range(R)]
    for r, c, v in zip(*[iter(RCV)] * 3):
        item[r - 1][c - 1] = v

    dp = [0] * (C + 1)
    for i in range(R):
        dp, dp_prev = [0] * (C + 1), dp
        v = [0] * 4
        for j in range(C):
            for k in range(4):
                if v[k] < dp_prev[j + 1]:
                    v[k] = dp_prev[j + 1]
            if item[i][j] > 0:
                for k in range(2, -1, -1):
                    if v[k + 1] < v[k] + item[i][j]:
                        v[k + 1] = v[k] + item[i][j]
            dp[j + 1] = v[3]

    print(dp[C])

    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    R, C, K, *RCV = map(int, read().split())

    item = dict()
    for r, c, v in zip(*[iter(RCV)] * 3):
        item[(r - 1, c - 1)] = v

    dp = [0] * (C + 1)
    for i in range(R):
        dp, dp_prev = [0] * (C + 1), dp
        v = [0] * 4
        for j in range(C):
            for k in range(4):
                if v[k] < dp_prev[j + 1]:
                    v[k] = dp_prev[j + 1]
            if (i, j) in item:
                for k in range(2, -1, -1):
                    if v[k + 1] < v[k] + item[(i, j)]:
                        v[k + 1] = v[k] + item[(i, j)]
            dp[j + 1] = v[3]

    print(dp[C])

    return


if __name__ == '__main__':
    main()

Solution (Python):


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

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

DP_prev = [0 for _ in range(C+1)]
DP1 = [0 for _ in range(C+1)]
DP2 = [0 for _ in range(C+1)]
DP3 = [0 for _ in range(C+1)]
for r in range(1,R+1):
  for c in range(1,C+1):
    item = items[r][c]
    DP1[c] = max(DP_prev[c]+item,DP1[c-1])
    DP2[c] = max(DP1[c],DP2[c-1],DP1[c-1]+item)
    DP3[c] = max(DP2[c],DP3[c-1],DP2[c-1]+item)
  DP_prev = DP3
        
print(DP_prev[C])

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

r,c,k = map(int,readline().split())
data = list(map(int,read().split()))
d = dict()
it = iter(data)
for ri,ci,vi in zip(it,it,it):
    d[(ri-1)*5000 + (ci-1)] = vi

dp_max = [0] * (c)

for i in range(r):
    dp = [0] * 4
    for j in range(c):
        dp[0] = max(dp[0],dp_max[j])
        if( i*5000+j  in d):
            ci = d[i*5000+j]
            for k in range(3,0,-1):
                dp[k] = max(dp[k], dp[k-1] + ci)

        dp_max[j] = max(dp)

print(dp_max[-1])

Solution (Python):
import sys
from collections import defaultdict
range = xrange
input = raw_input

inp = [int(x) for x in sys.stdin.read().split()]; ii = 0

n = inp[ii]; ii += 1
m = inp[ii]; ii += 1
k = inp[ii]; ii += 1

R = inp[ii + 0: ii + 3 * k: 3]
C = inp[ii + 1: ii + 3 * k: 3]
V = inp[ii + 2: ii + 3 * k: 3]

items = [defaultdict(list) for _ in range(n)]
for i in range(k):
    r = R[i] - 1
    c = C[i] - 1
    v = V[i]
    items[r][c].append(v)

DP0 = [0] * m
DP1 = [0] * m
DP2 = [0] * m
DP3 = [0] * m

for r in range(n):
    for c in range(m):
        if c:
            DP0[c] = max(DP0[c], DP0[c - 1])
            DP1[c] = max(DP1[c], DP1[c - 1])
            DP2[c] = max(DP2[c], DP2[c - 1])
            DP3[c] = max(DP3[c], DP3[c - 1])
        if c in items[r]:
            for v in items[r][c]:
                DP3[c] = max(DP3[c], DP2[c] + v)
                DP2[c] = max(DP2[c], DP1[c] + v)
                DP1[c] = max(DP1[c], DP0[c] + v)
    for c in range(m):
        DP0[c] = max(DP0[c], DP1[c], DP2[c], DP3[c])
print DP0[-1]

Solution (Python):


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

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

DP_prev = [0 for _ in range(C+1)]
for r in range(1,R+1):
  DP1 = [0 for _ in range(C+1)]
  DP2 = [0 for _ in range(C+1)]
  DP3 = [0 for _ in range(C+1)]
  for c in range(1,C+1):
    item = items[r][c]
    DP1[c] = max(DP_prev[c]+item,DP1[c-1])
    DP2[c] = max(DP1[c],DP2[c-1],DP1[c-1]+item)
    DP3[c] = max(DP2[c],DP3[c-1],DP2[c-1]+item)
  DP_prev = DP3
        
print(DP_prev[C])

Solution (Python):
R, C, K = map(int, input().split())
A = [[0] * 4 for _ in range(C+1)]
B = [[-1] * (C+1) for _ in range(R+1)]
for k in range(K):
    r, c, v = map(int, input().split())
    B[r][c] = v

for r in range(1, R+1):
    D = A[:]
    for c in range(1, C+1):
        if B[r][c] == -1:
            A[c][0] = max(A[c-1][0], max(D[c]))
            A[c][1] = max(A[c-1][1], max(D[c]))
            A[c][2] = max(A[c-1][2], max(D[c])) 
            A[c][3] = max(A[c-1][3], max(D[c]))
        else:
            A[c][0] = max(A[c-1][0], max(D[c]))
            A[c][1] = max(A[c-1][1], A[c-1][0]+B[r][c], max(D[c])+B[r][c])
            A[c][2] = max(A[c-1][2], A[c-1][1]+B[r][c])
            A[c][3] = max(A[c-1][3], A[c-1][2]+B[r][c])
print(max(A[-1]))

Solution (Python):
import sys
input=lambda: sys.stdin.readline().rstrip()

r,c,k=map(int,input().split())
D=[[0]*c for _ in range(r)] 
for _ in range(k):
	ri,ci,v=map(int,input().split())
	ri-=1
	ci-=1
	D[ri][ci]=v

DP0=[[0]*(c+1) for i in range(r+1)]
DP1=[[0]*(c+1) for i in range(r+1)]
DP2=[[0]*(c+1) for i in range(r+1)]
DP3=[[0]*(c+1) for i in range(r+1)]
for i in range(r):
	for j in range(c):
		v=D[i][j]
		if v!=0:
			DP1[i][j]=max(DP0[i-1][j],DP1[i-1][j],DP2[i-1][j],DP3[i-1][j])+v

		DP0[i][j]=max(DP0[i][j],DP0[i-1][j],DP1[i-1][j],DP2[i-1][j],DP3[i-1][j])
		if v!=0:
			DP1[i][j]=max(DP1[i][j],DP0[i-1][j]+v,DP1[i-1][j]+v,DP2[i-1][j]+v,DP3[i-1][j]+v)
		DP0[i][j]=max(DP0[i][j],DP0[i][j-1])
		DP1[i][j]=max(DP1[i][j],DP1[i][j-1])
		DP2[i][j]=max(DP2[i][j],DP2[i][j-1])
		DP3[i][j]=max(DP3[i][j],DP3[i][j-1])
		if v!=0:
			DP1[i][j]=max(DP1[i][j],DP0[i][j-1]+v)
			DP2[i][j]=max(DP2[i][j],DP1[i][j-1]+v)
			DP3[i][j]=max(DP3[i][j],DP2[i][j-1]+v)
		
ans=max(DP0[r-1][c-1],DP1[r-1][c-1],DP2[r-1][c-1],DP3[r-1][c-1])
print(ans)

Solution (Python):


import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

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

for i in range(R):
    DPi = [None] * C
    for j in range(C):
        DPi[j] = [0,0,0,0]
        DPij = DPi[j]
        DPijs1 = DPi[j-1]
        if i != 0 and j != 0:
            DPij[0] = max(DPLast[j][0],DPLast[j][1],DPLast[j][2],DPLast[j][3],DPijs1[0])
            DPij[1] = DPijs1[1]
            DPij[2] = DPijs1[2]
            DPij[3] = DPijs1[3]
            if Gift[i][j]:
                DPij[3] = max(DPij[3],DPij[2] + Gift[i][j])
                DPij[2] = max(DPij[2],DPij[1] + Gift[i][j])
                DPij[1] = max(DPij[1],DPij[0] + Gift[i][j])
        elif i == 0 and j != 0:
            DPij[0] = DPijs1[0]
            DPij[1] = DPijs1[1]
            DPij[2] = DPijs1[2]
            DPij[3] = DPijs1[3]
            if Gift[i][j]:
                DPij[3] = max(DPij[3],DPij[2] + Gift[i][j])
                DPij[2] = max(DPij[2],DPij[1] + Gift[i][j])
                DPij[1] = max(DPij[1],DPij[0] + Gift[i][j])
        elif j == 0 and i != 0:
            DPij[0] = max(DPLast[j][0],DPLast[j][1],DPLast[j][2],DPLast[j][3])
            if Gift[i][j]:
                DPij[3] = max(DPij[3],DPij[2] + Gift[i][j])
                DPij[2] = max(DPij[2],DPij[1] + Gift[i][j])
                DPij[1] = max(DPij[1],DPij[0] + Gift[i][j])
        else:
            DPij[1] = Gift[i][j]
    DPLast = DPi

print(max(DPi[C-1]))

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

dp = [[0 for i in range(4)] for j in range(C+1)]
for r in range(1, R+1):
	for c in range(1, C+1):
		v = V[r][c]
		under_val = max(dp[c])
		dp[c][0] = max(under_val, dp[c-1][0])
		if v > 0:
			dp[c][1] = max(under_val + v, dp[c-1][0] + v, dp[c-1][1])
			dp[c][2] = max(dp[c-1][1] + v, dp[c-1][2])
			dp[c][3] = max(dp[c-1][2] + v, dp[c-1][3])
		else:
			dp[c][1] = dp[c-1][1]
			dp[c][2] = dp[c-1][2]
			dp[c][3] = dp[c-1][3]
print(max(dp[-1]))

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


def solve():
    memo = [[0] * 4 for _ in range(C+1)]
    prev = [[0] * 4 for _ in range(C+1)]
    for r in range(1,R+1):
        prev, memo = memo, prev
        for c in range(1,C+1):
            v = RC[r-1][c-1]
            memo[c][0] = max(prev[c][3], memo[c-1][0])
            memo[c][1] = max(memo[c][0] + v, memo[c-1][1])
            memo[c][2] = max(memo[c][1], memo[c-1][1] + v, memo[c-1][2])
            memo[c][3] = max(memo[c][2], memo[c-1][2] + v, memo[c-1][3])
    return memo[-1][3]

if __name__ == "__main__":
    print(solve())

Solution (Python):
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    R, C, K, *RCV = map(int, read().split())

    item = dict()
    for r, c, v in zip(*[iter(RCV)] * 3):
        item[(r - 1, c - 1)] = v

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

    print(dp[R][C])

    return


if __name__ == '__main__':
    main()

Solution (Python):


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

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





dp = [0] * (C+1)
for r in range(1, R+1):
    tmp0 = 0
    tmp1 = 0
    tmp2 = 0
    tmp3 = 0
    V[r-1].sort()
    for c, v in V[r-1]:
        tmp0 = max(dp[c], tmp0)
        tmp1 = max(dp[c], tmp1)
        tmp2 = max(dp[c], tmp2)
        tmp3 = max(dp[c], tmp3)

        tmp3 = max(tmp3, tmp2+v)
        tmp2 = max(tmp2, tmp1+v)
        tmp1 = max(tmp1, tmp0+v)

        dp[c] = max(tmp0, tmp1, tmp2, tmp3)
    for i in range(1, C+1):
        dp[i] = max(dp[i], dp[i-1])
    

print(dp[-1])

Solution (Python):
r, c, k = map(int, input().split())
v = [map(int, input().split()) for _ in range(k)]

sq = [[0 for _ in range(c)] for _ in range(r)]
for ri, ci, vi in v:
    sq[ri - 1][ci - 1] = vi

dp = [[[0 for _ in range(c)] for _ in range(4)] for _ in range(2)]
for ri in range(r):
    if 0 < ri:
        for ci in range(c):
            dp[ri % 2][0][ci] = max([dp[1 - ri % 2][i][ci] for i in range(4)])
            for i in range(1, 4):
                dp[ri % 2][i][ci] = 0
    for ci in range(c):
        if 0 < ci:
            for i in range(4):
                dp[ri % 2][i][ci] = max(dp[ri % 2][i][ci], dp[ri % 2][i][ci - 1])
        if 0 < sq[ri][ci]:
            for i in range(2, -1, -1):
                dp[ri % 2][i + 1][ci] = max(dp[ri % 2][i + 1][ci], dp[ri % 2][i][ci] + sq[ri][ci])

ans = max([dp[ri % 2][i][-1] for i in range(4)])
print(ans)

Solution (Python):


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

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

DP_prev = [0 for _ in range(C+1)]

for r in range(1,R+1):
  DP = [[0 for _ in range(C+1)],[0 for _ in range(C+1)],[0 for _ in range(C+1)]]
  for c in range(1,C+1):
    item = items[r][c]
    DP1 = max(DP_prev[c]+item,DP[0][c-1])
    DP2 = max(DP1,DP[1][c-1],DP[0][c-1]+item)
    DP3 = max(DP2,DP[2][c-1],DP[1][c-1]+item)
    DP[0][c] = DP1
    DP[1][c] = DP2
    DP[2][c] = DP3
  DP_prev = DP[2]
        
print(DP_prev[C])

Solution (Python):
import sys
sys.setrecursionlimit(10**7) 
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right

from collections import deque, defaultdict


from collections import Counter

from itertools import accumulate,combinations,permutations,product

from heapq import heapify,heappop,heappush

from functools import reduce,lru_cache

from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printe(*x):print("
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def binr(x): return bin(x)[2:]
def bitcount(x): 
    x= x - ((x >> 1) & 0x5555555555555555)
    x= (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x= (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f 
    x+= (x >> 8); x+= (x >> 16); x+= (x >> 32) 
    return x & 0x7f

def main():
    mod = 1000000007
    

    
    R,C,K = map(int, input().split())
    
    
    base=5000
    S=[]
    for i in range(K):
        r,c,v = map(int, input().split())
        r-=1
        c-=1
        S.append((r*base+c,v))

    S.sort(key=itemgetter(0))


    p=0
    dp=[[0] * 4 for _ in range(C)]
    dpi=[[0] * 4 for _ in range(C)]
    for i in range(R):
        for j in range(C):
            cv=0
            if p<K and i*base+j==S[p][0]:
                cv=S[p][1]
                p+=1
            if j>0:
                dpi[j]=copy(dpi[j-1])
            else:
                dpi[0]=[0] * 4 
            if i>0:
                dpi[j][0]=max(dp[j],dpi[j][0])
            if cv!=0:
                for k in range(2,-1,-1):
                    dpi[j][k+1]=max(dpi[j][k]+cv,dpi[j][k+1])
                
            dp[j]=max(dpi[j])
    print(dp[-1])



if __name__ == "__main__":
    main()

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]



def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count





R,C,K = IL()
data = [[0 for i in range(C)] for j in range(R)]
for _ in range(K):
  j,i,v = IL()
  data[j-1][i-1] = v

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