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
input = sys.stdin.buffer.readline
H, W, K = map(int, input().split())
B = {}
for _ in range(K):
    r, c, v = map(int, input().split())
    B[(r, c)] = v

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

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

print(max(dp[-1]))

Solution (Python):
import sys
input = sys.stdin.buffer.readline
H, W, K = map(int, input().split())
B = {}
for _ in range(K):
    r, c, v = map(int, input().split())
    B[(r, c)] = v

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

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

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

Solution (Python):
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

R, C, K = mapint()
last_dp = [[0]*4 for _ in range(C)]
dic = [[0]*C for _ in range(R)]
for _ in range(K):
    r, c, v = mapint()
    dic[r-1][c-1] = v

for r in range(R):
    dp = [[0]*4 for _ in range(C)]
    for c in range(C):
        v = dic[r][c]
        for i in range(4):
            if c!=0:
                dp[c][i] = dp[c-1][i]
            if r!=0:
                dp[c][0] = max(dp[c][0], last_dp[c][i])
        if v!=0:
            for i in range(2, -1, -1):
                dp[c][i+1] = max(dp[c][i+1], dp[c][i]+v)
    last_dp = dp

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

Solution (Python):
import sys
input=sys.stdin.readline
def main():
    r,c,k=map(int,input().split())
    v=[[0]*c for _ in range(r)]
    for _ in range(k):
        ri,ci,a=map(int,input().split())
        ri-=1
        ci-=1
        v[ri][ci]=a
    dp=[[[0]*c for _ in range(r)] for i in range(4)]
    
    if v[0][0]>0:
        dp[1][0][0]=v[0][0]
    for i in range(r):
        for j in range(c):
            for k in range(4):
                if i>0:
                    dp[1][i][j]=max(dp[1][i][j],dp[k][i-1][j]+v[i][j])
                    dp[0][i][j]=max(dp[0][i][j],dp[k][i-1][j])
                if j>0:
                    if k>0:
                        dp[k][i][j]=max(dp[k][i][j],dp[k-1][i][j-1]+v[i][j])
                    dp[k][i][j]=max(dp[k][i][j],dp[k][i][j-1])
    
    ans=0
    for i in range(4):
        ans=max(dp[i][r-1][c-1],ans)
    return print(ans)
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]
    m = max(dpprev[i+1])
    if v == 0:
      dp[i+1][0] = max(dp[i][0],m)
      dp[i+1][1] = max(dp[i][1],m)
      dp[i+1][2] = max(dp[i][2],m)
      dp[i+1][3] = max(dp[i][3],m)
    else:
      dp[i+1][0] = max(dp[i][0],m)
      dp[i+1][1] = max(dp[i][1],dp[i][0]+v,m+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]))

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

Solution (Python):
R,C,K = map(int,input().split())
dp0 = [[0 for _ in range(C+1)] for f in range(R+1)]
dp1 = [[0 for _ in range(C+1)] for f in range(R+1)]
dp2 = [[0 for _ in range(C+1)] for f in range(R+1)]
dp3 = [[0 for _ in range(C+1)] for f in range(R+1)]
vl = [[0 for _ in range(C+1)] for f in range(R+1)]

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

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

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

Solution (Python):
import sys

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

class SegmentTree:
    def __init__(self, data, default=0, func=max):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        """func of data[start, stop)"""
        start += self._size
        stop += self._size

        res_left = res_right = self._default
        while start < stop:
            if start & 1:
                res_left = self._func(res_left, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res_right = self._func(self.data[stop], res_right)
            start >>= 1
            stop >>= 1

        return self._func(res_left, res_right)

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

shift = int(10**9 + 1)
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*shift+v)
for i in range(rows+1):
	items[i].sort()
S = SegmentTree(best)
ans = 0
for r in range(1, rows+1):
	dp = []
	best1, best2 = 0, 0
	Row = items[r]
	for X in Row:
		c, v = X//shift, X%shift
		v1 = S.query(1, c+1) + 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)):
		c = Row[j]//shift
		if S[c] < dp[j]:
			S[c] = dp[j]
print(ans)

Solution (Python):
import sys
input=sys.stdin.readline
def main():
	R,C,K=map(int,input().split())
	lis=[[0]*(C) for i in range(R)]
	for i in range(K):
		a,b,c=map(int,input().split())
		lis[a-1][b-1]=c
	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(1,R+1):
		for j in range(1,C+1):
			for x,y in ((dp0,0),(dp1,dp0),(dp2,dp1),(dp3,dp2)):
				t=lis[i-1][j-1]
				x[i][j]=max(x[i-1][j],x[i][j])
				x[i][j]=max(x[i][j-1],x[i][j])
				if t!=0:
					dp1[i][j]=max(dp1[i][j],x[i-1][j]+t)
					if y!=0:
						x[i][j]=max(x[i][j],y[i][j-1]+t)
	print(max(dp0[-1][-1],dp1[-1][-1],dp2[-1][-1],dp3[-1][-1]))
if __name__ == '__main__':
	main()

Solution (Python):
R,C,k = map(int,input().split())
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(k):
    r,c,v = map(int,input().split())
    dp1[r][c] = v
for i in range(1,R+1):
    for j in range(1,C+1):
        a = dp1[i][j]
        dp3[i][j] = max(dp2[i][j-1]+a,dp3[i][j-1])
        dp2[i][j] = max(dp1[i][j-1]+a,dp2[i][j-1])
        dp1[i][j] = max(dp1[i-1][j]+a,dp2[i-1][j]+a,dp3[i-1][j]+a,dp1[i][j-1],a)
print(max(dp1[R][C],dp2[R][C],dp3[R][C]))

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

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

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

    dp0=[[-10**10]*c  for i in range(r)]
    dp1 = [[-10 ** 10] * c for i in range(r)]
    dp2 = [[-10 ** 10] * c for i in range(r)]
    dp3 = [[-10 ** 10] * c for i in range(r)]

    if item[0][0]==0:
        dp0[0][0]=0
    else:
        dp0[0][0]=0
        dp1[0][0]=item[0][0]

    for i in range(r):
        for j in range(c):
            if j!=c-1:
                v=item[i][j+1]
                if v==0:
                    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])
                else:
                    dp0[i][j+1]=max(dp0[i][j],dp0[i][j+1])
                    dp1[i][j+1]=max(dp0[i][j]+v,dp1[i][j],dp1[i][j+1])
                    dp2[i][j + 1] = max(dp1[i][j] + v, dp2[i][j], dp2[i][j + 1])
                    dp3[i][j + 1] = max(dp2[i][j] + v, dp3[i][j], dp3[i][j + 1])
            if i!=r-1:
                v=item[i+1][j]
                if v==0:
                    dp0[i+1][j]=max(dp0[i][j],dp1[i][j],dp2[i][j],dp3[i][j],dp0[i+1][j])
                else:
                    dp0[i+1][j]=max(dp0[i][j],dp1[i][j],dp2[i][j],dp3[i][j],dp0[i+1][j])
                    dp1[i + 1][j] = max(dp0[i][j]+v, dp1[i][j]+v, dp2[i][j]+v, dp3[i][j]+v, dp1[i + 1][j])

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

if __name__=='__main__':
    main()

Solution (Python):
R,C,k = map(int,input().split())
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)]
item = [[0]*(C+1) for i in range(R+1)]
for i in range(k):
    r,c,v = map(int,input().split())
    dp1[r][c] = v

for i in range(1,R+1):
    for j in range(1,C+1):
        a = dp1[i][j]
        dp3[i][j] = max(dp2[i][j-1]+a,dp3[i][j-1])
        dp2[i][j] = max(dp1[i][j-1]+a,dp2[i][j-1])
        dp1[i][j] = max(dp1[i-1][j]+a,dp2[i-1][j]+a,dp3[i-1][j]+a,dp1[i][j-1],a)

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

Solution (Python):
R,C,k = map(int,input().split())
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)]
item = [[0]*(C+1) for i in range(R+1)]
for i in range(k):
    r,c,v = map(int,input().split())
    
    dp1[r][c] = v

    

for i in range(1,R+1):
    for j in range(1,C+1):
        
        
        
        
        
        
        dp3[i][j] = max(dp2[i][j-1]+dp1[i][j],dp3[i][j-1])
        dp2[i][j] = max(dp1[i][j-1]+dp1[i][j],dp2[i][j-1])
        dp1[i][j] = max(dp1[i-1][j]+dp1[i][j],dp2[i-1][j]+dp1[i][j],dp3[i-1][j]+dp1[i][j],dp1[i][j-1],dp1[i][j])
        
        



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

Solution (Python):
import sys


def input():
    return sys.stdin.readline().rstrip()


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

    field = [[0 for j in range(C)] for i in range(R)]

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

    dp = [[0] * 4 for j in range(C)]

    for i in range(R):
        for j in range(C):
            ct = field[i][j]
            premax = max(dp[j])

            if ct == 0:
                if j>0:
                    dp[j][0] = max(dp[j - 1][0], premax)
                else:
                    dp[j][0] = premax

                for k in range(1, 4):
                    if j > 0:
                        dp[j][k] = dp[j - 1][k]
            else:
                if j>0:
                    dp[j][0] = max(dp[j - 1][0], premax)
                    dp[j][1] = max(ct + max(dp[j - 1][0], premax), dp[j - 1][1])
                else:
                    dp[j][0] = premax
                    dp[j][1] = premax +ct
                for k in range(2, 4):
                    if j > 0:
                        dp[j][k] = max(dp[j - 1][k - 1] + ct, dp[j - 1][k])

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


if __name__ == "__main__":
    main()

Solution (Python):
import sys

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

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

for r in range(R-1, -1, -1):
    
    
    
    for c in range(C-1, -1, -1):
        v = values[r][c]
        for i in range(4):
            if i == 0 or v == 0:
                dp[i][r][c] = max(dp[3][r+1][c], dp[i][r][c+1])
            else:
                dp[i][r][c] = max(dp[3][r + 1][c]+v, dp[i][r][c + 1], dp[i-1][r][c + 1] + v)

print(dp[3][0][0])

Solution (Python):


import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

r, c, k = LI()
maze = [[0] * c for _ in range(r)]
for _ in range(k):
    R, C, V = LI()
    maze[R-1][C-1] = V

dp1 = [[0] * (c+1) for _ in range(r+1)]
dp2 = [[0] * (c+1) for _ in range(r+1)]
dp3 = [[0] * (c+1) for _ in range(r+1)]

for i in range(1, r+1):
    for j in range(1, c+1):
        dp1[i][j] = max(dp1[i][j-1], dp1[i-1][j] + maze[i-1][j-1], maze[i-1][j-1], dp2[i-1][j] + maze[i-1][j-1], dp3[i-1][j] + maze[i-1][j-1])
        dp2[i][j] = max(dp2[i][j-1], dp2[i-1][j], dp1[i][j-1] + maze[i-1][j-1])
        dp3[i][j] = max(dp3[i][j-1], dp3[i-1][j], dp2[i][j-1] + maze[i-1][j-1])
ans = max(dp1[-1][-1], dp2[-1][-1], dp3[-1][-1])
print(ans)

Solution (Python):

import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

R, C, K = map(int, readline().split())
rcv = list(map(int, read().split()))
rr = rcv[::3]
cc = rcv[1::3]
vv = rcv[2::3]
rc2v = {}
for _r, _c, _v in zip(rr, cc, vv):
    rc2v[(_r-1, _c-1)] = _v

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

for r in range(R):
    for c in range(C):
        if(c!=0):
            dp[c][0] = max(dp[c-1][0], max(dp[c]))
        else:
            dp[c][0] = max(dp[c])

        v = 0
        if (r, c) in rc2v:
            v = rc2v[(r, c)]
        for k in range(1,4):
            if(c!=0):
                dp[c][k] = max(dp[c-1][k], dp[c-1][k-1] + v, dp[c][0] + v)
            else:
                dp[c][k] = dp[c][0] + v

print(max(dp[-1]))

Solution (Python):
def main():

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

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

    for i in range(R):
        for j in range(C):
            v = max(dp[0][j+1])
            u = 0
            if (i, j) in a: u = a[(i, j)]
            dp[1][j+1][0] = max(dp[1][j+1][0], v)
            dp[1][j+1][1] = max(dp[1][j+1][1], dp[1][j][1], dp[1][j][0] + u,  v + u)
            dp[1][j+1][2] = max(dp[1][j+1][2], dp[1][j][2], dp[1][j][1] + u )
            dp[1][j+1][3] = max(dp[1][j+1][3], dp[1][j][3], dp[1][j][2] + u )
        dp[1], dp[0] = dp[0], dp[1]

    return max(dp[0][C])

if __name__ == '__main__':
    print(main())

Solution (Python):
R,C,K = map(int,input().split())
J=[0] * K
for i in range(K):
  J[i] = list(map(int,input().split()))


DP1 = [[0]*(C+2) for i in range(R+2)]
DP2 = [[0]*(C+2) for i in range(R+2)]
DP3 = [[0]*(C+2) for i in range(R+2)]

MAP = [[0]*C for i in range(R)]

for x,y,v in J:
    MAP[x-1][y-1] = v

for i in range(R):
    for j in range(C):
        DP1[i][j] = max(DP1[i][j-1],DP1[i-1][j]+MAP[i][j],DP2[i-1][j]+MAP[i][j],DP3[i-1][j]+MAP[i][j])
        DP2[i][j] = max(DP2[i][j-1],DP1[i][j-1]+MAP[i][j])
        DP3[i][j] = max(DP3[i][j-1],DP2[i][j-1]+MAP[i][j])




ANS=0
for i in range(R):
    for j in range(C):
        ANS=max(ANS,DP1[i][j],DP2[i][j],DP3[i][j])
print(ANS)

Solution (Python):
import sys

input=sys.stdin.readline

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

dp=[[0 for i in range(3)] for j in range(C)]
dp[C-1][0]=item[R-1][C-1]
dp[C-1][1]=item[R-1][C-1]
dp[C-1][2]=item[R-1][C-1]

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


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

print(dp[0][0])

Solution (Python):
import sys
input = sys.stdin.readline
def solve():
  R, C, K = map(int, input().split())
  item = [[0]*C for _ in range(R)]
  for i in range(K):
    r,c,v = map(int, input().split())
    item[r-1][c-1] = v
  dp = [[[0]*(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 k in range(4): 
        dp[k][i][j] = dp[k][i][j-1]
      
      dp[0][i][j] = max(dp[0][i][j],dp[-1][i-1][j])
      if item[i-1][j-1]>0:
        
        dp[1][i][j] = max(dp[1][i][j],dp[-1][i-1][j]+item[i-1][j-1])
        for k in range(1,4): 
          dp[k][i][j] = max(dp[k][i][j],dp[k-1][i][j-1]+item[i-1][j-1])
      for k in range(1,4):
        dp[k][i][j] = max(dp[k-1][i][j],dp[k][i][j])
  ans = 0
  for k in range(4):
    ans = max(ans,dp[k][-1][-1])
  return ans
print(solve())

Solution (Python):
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())

R,C,K = MI()
item = [[0]*(C+1) for _ in range(R+1)]
for i in range(K):
    r,c,v = MI()
    item[r][c] = v

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

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

ans = 0
for j in range(4):
    ans = max(ans,dp[R][j][C])

print(ans)

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

DP=[[[0]*(c+1) for _ in range(r+1)] for i in range(4)]
for i in range(r):
	for j in range(c):
		v=D[i][j]

		for ii in range(4):
			DP[0][i][j]=max(DP[0][i][j],DP[ii][i-1][j])
			if v!=0:
				DP[1][i][j]=max(DP[1][i][j],DP[ii][i-1][j]+v)

			DP[ii][i][j]=max(DP[ii][i][j],DP[ii][i][j-1])
			if v!=0 and ii!=0:
				DP[ii][i][j]=max(DP[ii][i][j],DP[ii-1][i][j-1]+v)
ans=0
for i in range(4):
	ans=max(ans,DP[i][r-1][c-1])
print(ans)

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

Solution (Python):
import sys

inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
shift = int(10**9 + 1)
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*shift+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 X in Row:
		c, v = X//shift, X%shift
		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)):
		c = Row[j]//shift
		if best[c] < dp[j]:
			best[c] = 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
input = sys.stdin.readline

R, C, K = map(int, input().split())
items = [[0] * (C+1) for _ in range(R+1)]
for _ in range(K):
    r, c, v = map(int, input().split())
    items[r][c] = v
dp = [[0] * 4 for _ in range(C+1)]
for i in range(1, R+1):
    ndp = [[0] * 4 for _ in range(C+1)]
    for j in range(1, C+1):
        for k in range(4):
            ndp[j][0] = max(ndp[j][0], dp[j][k])
            ndp[j][k] = max(ndp[j][k], ndp[j-1][k])
        if items[i][j]:
            for k in range(3, 0, -1):
                ndp[j][k] = max(ndp[j][k], ndp[j][k-1] + items[i][j])
    dp = ndp
print(max(dp[C]))

Solution (Python):
import sys
read = sys.stdin.buffer.read
readlines = sys.stdin.buffer.readlines
input = sys.stdin.buffer.readline
H, W, K = map(int, input().split())
B = {}

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

dp = [[0]*(W+1) for _ in range(4)]
 
for i in range(H):
    for j in range(W):
        if (i, j) in B:
            v = B[(i, j)]
            dp[0][j+1] = max(dp[0][j], dp[0][j+1], dp[1][j+1], dp[2][j+1], dp[3][j+1])
            dp[1][j+1] = max(dp[1][j], dp[0][j+1]+v)
            dp[2][j+1] = max(dp[2][j], dp[1][j]+v)
            dp[3][j+1] = max(dp[3][j], dp[2][j]+v)
        else:
            dp[0][j+1] = max(dp[0][j], dp[0][j+1], dp[1][j+1], dp[2][j+1], dp[3][j+1])
            dp[1][j+1] = dp[1][j]
            dp[2][j+1] = dp[2][j]
            dp[3][j+1] = dp[3][j]
print(max(dp[i][-1] for i in range(4)))