Problem:


Score : 500 points

Problem Statement

There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i.

Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square).

He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.

Find the maximum possible sum of the values of items he picks up.

Constraints

1 \leq R, C \leq 3000

1 \leq K \leq \min(2 \times 10^5, R \times C)

1 \leq r_i \leq R

1 \leq c_i \leq C

(r_i, c_i) \neq (r_j, c_j) (i \neq j)

1 \leq v_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R C K
r_1 c_1 v_1
r_2 c_2 v_2
:
r_K c_K v_K

Output

Print the maximum possible sum of the values of items Takahashi picks up.

Sample Input 1

2 2 3
1 1 3
2 1 4
1 2 5

Sample Output 1

8

He has two ways to get to the goal:

Visit (1, 1), (1, 2), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 5 = 8.

Visit (1, 1), (2, 1), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 4 = 7.

Thus, the maximum possible sum of the values of items he picks up is 8.

Sample Input 2

2 5 5
1 1 3
2 4 20
1 2 1
1 3 4
1 4 2

Sample Output 2

29

We have four items in the 1-st row. The optimal choices are as follows:

Visit (1, 1) (1, 2), (1, 3), (1, 4), (2, 4), and (2, 5), in this order, and pick up all items except the one on (1, 2). Then, the total value of the items he picks up will be 3 + 4 + 2 + 20 = 29.

Sample Input 3

4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10

Sample Output 3

142



Sample input:
2 2 3
1 1 3
2 1 4
1 2 5


Sample output:
8

Submission status: Time Limit Exceeded

Solution code:
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(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    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): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    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)]

dp = [[[0 for k in range(4)] for j in range(c)] for i in range(r)]

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

for i in range(r):
    for j in range(c):
        if i == 0 and j == 0:
            continue
        if i == 0:
            if item[i][j] != 0:
                for k in range(4):
                    if k == 0:
                        dp[i][j][k] = dp[i][j-1][k]
                    else:
                        dp[i][j][k] = max(dp[i][j-1][k],dp[i][j-1][k-1] + item[i][j])

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

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

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

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


ans = 0

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

Submission status: Time Limit Exceeded

Solution code:
R, C, K = map(int, input().split())
# = int(input())
p = []
for k in range(K):
  p.append(list(map(int, input().split())))
nextlist = [[0, 0]]

maps = [[0 for _ in range(C)] for _ in range(R)]
for k in range(K):
  maps[p[k][0]-1][p[k][1]-1] += p[k][2]

point = [[[0, 0, 0] for _ in range(C)] for _ in range(R)]

point[0][0][0] = maps[0][0]

for k in range(R + C):
  for r in range(max(0, k - C + 1), min(k+1, R)):
    c = k - r
    a, b, d = point[r][c][0], point[r][c][1], point[r][c][2] 
    if r < R - 1:
      point[r+1][c][0] = max(point[r+1][c][0], maps[r+1][c] + max(a, b, d))      
    if c < C - 1:
      point[r][c+1][0] = max(point[r][c+1][0], maps[r][c+1], a)
      point[r][c+1][1] = max(point[r][c+1][1], a + maps[r][c+1], b)
      point[r][c+1][2] = max(point[r][c+1][2], b + maps[r][c+1], d)


print(max(point[-1][-1][0:3]))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

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

#############
# Functions #
#############

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


#####Shorten#####
def DD(arg): return defaultdict(arg)

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

######Combination######
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

######Factorization######
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

#####MakeDivisors######
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

#####MakePrimes######
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

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

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

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

#####ChangeBase#####
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]

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

#############
# Main Code #
#############
base = 3000*3*10**10
@lru_cache(maxsize=None)
def decode(x):
  a = x%base
  x //= base
  b = x%base
  x //= base
  c = x%base
  x //= base
  d = x%base
  return [a,b,c,d]

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 for i in range(C+1)] for j in range(R+1)]
for j in range(R):
  for i in range(C):
    v = data[j][i] 
    if v == 0:
      dp[j+1][i+1] += max(decode(dp[j+1][i])[0],max(decode(dp[j][i+1])))
      dp[j+1][i+1] += max(decode(dp[j+1][i])[1],max(decode(dp[j][i+1])))*base
      dp[j+1][i+1] += max(decode(dp[j+1][i])[2],max(decode(dp[j][i+1])))*base**2
      dp[j+1][i+1] += max(decode(dp[j+1][i])[3],max(decode(dp[j][i+1])))*base**3
    else:
      dp[j+1][i+1] += max(decode(dp[j+1][i])[0],max(decode(dp[j][i+1])))
      dp[j+1][i+1] += max(decode(dp[j+1][i])[1],decode(dp[j+1][i])[0]+v,max(decode(dp[j][i+1]))+v)*base
      dp[j+1][i+1] += max(decode(dp[j+1][i])[2],decode(dp[j+1][i])[1]+v,max(decode(dp[j][i+1]))+v)*base**2
      dp[j+1][i+1] += max(decode(dp[j+1][i])[3],decode(dp[j+1][i])[2]+v,max(decode(dp[j][i+1]))+v)*base**3
print(max(decode(dp[-1][-1])))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


import sys
sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(R, C, K, RCV):

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

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

    for i in range(R):
        for j in range(C):
            for p in range(4):
                memo[i][j+1][p] = max(memo[i][j+1][p], memo[i][j][p])
                memo[i+1][j][0] = max(memo[i+1][j][0], memo[i][j][p])
                if p != 3:
                    memo[i][j+1][p+1] = max(memo[i][j+1][p+1], memo[i][j][p] + V[i][j])
                    memo[i+1][j][0] = max(memo[i+1][j][0], memo[i][j][p] + V[i][j])

    return max(memo[R-1][C])

def main():
    R, C, K = read_int_n()
    RCV = [read_int_n() for _ in range(K)]
    print(slv(R, C, K, RCV))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline

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

# dp[taken 0 - 2][R][C]
dp = [[-1] * (C + 1) * (R + 1) for _ in range(4)]
dp[0][0] = 0
for j in range(C):
    for i in range(R):
        for k in range(4):
            ij = i * C + j
            ij1 = i * C + j + 1
            i1j = (i + 1) * C + j
            # Use
            if field[i][j] and k < 3:
                dp[k+1][ij1] = max(dp[k+1][ij1], dp[k][ij] + field[i][j]) 
                dp[0][i1j] = max(dp[0][i1j], dp[k][ij] + field[i][j]) 
            # No use down
            dp[0][i1j] = max(dp[0][i1j], dp[k][ij]) 
            # No use right
            dp[k][ij1] = max(dp[k][ij1], dp[k][ij]) 

ans = 0
for i in range(4):
    for j in range(R + 1):
        ans = max(ans, dp[i][j * C + C - 1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
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(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    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): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    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)]

dp = [[[0 for k in range(4)] for j in range(c)] for i in range(r)]

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

for i in range(r):
    for j in range(c):
        if i == 0 and j == 0:
            continue
        if i == 0:
            if item[i][j] != 0:
                for k in range(4):
                    if k == 0:
                        dp[i][j][k] = dp[i][j-1][k]
                    else:
                        dp[i][j][k] = max(dp[i][j-1][k],dp[i][j-1][k-1] + item[i][j])

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

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

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

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


ans = 0

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

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
r,c,K=map(int, input().split())
grid=[[0]*(c+1) for _ in range(r+1)]
for i in range(K):
    ri,ci,vi=map(int, input().split())
    grid[ri][ci]=vi

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

for i in range(1,r+1):
    for j in range(1,c+1):
        dp[i][j][0]=max(dp[i][j][0],dp[i-1][j][0],dp[i-1][j][1],
        dp[i-1][j][2],dp[i-1][j][3])
        for k in range(4):
            dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k])
        if grid[i][j]!=0:
            dp[i][j][1]=max(dp[i][j][1],max(dp[i-1][j])+grid[i][j])
            for k in range(1,4):
                dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k-1]+grid[i][j])

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

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

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

#############
# Functions #
#############

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


#####Shorten#####
def DD(arg): return defaultdict(arg)

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

######Combination######
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

######Factorization######
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

#####MakeDivisors######
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

#####MakePrimes######
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

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

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

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

#####ChangeBase#####
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]

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

#############
# Main Code #
#############
base = 10**20
@lru_cache(maxsize=None)
def decode(x):
  a = x%base
  x //= base
  b = x%base
  x //= base
  c = x%base
  x //= base
  d = x%base
  return [a,b,c,d]

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 for i in range(C+1)] for j in range(R+1)]
for j in range(R):
  for i in range(C):
    v = data[j][i] 
    if v == 0:
      dp[j+1][i+1] += max(decode(dp[j+1][i])[0],max(decode(dp[j][i+1])))
      dp[j+1][i+1] += max(decode(dp[j+1][i])[1],max(decode(dp[j][i+1])))*base
      dp[j+1][i+1] += max(decode(dp[j+1][i])[2],max(decode(dp[j][i+1])))*base**2
      dp[j+1][i+1] += max(decode(dp[j+1][i])[3],max(decode(dp[j][i+1])))*base**3
    else:
      dp[j+1][i+1] += max(decode(dp[j+1][i])[0],max(decode(dp[j][i+1])))
      dp[j+1][i+1] += max(decode(dp[j+1][i])[1],decode(dp[j+1][i])[0]+v,max(decode(dp[j][i+1]))+v)*base
      dp[j+1][i+1] += max(decode(dp[j+1][i])[2],decode(dp[j+1][i])[1]+v,max(decode(dp[j][i+1]))+v)*base**2
      dp[j+1][i+1] += max(decode(dp[j+1][i])[3],decode(dp[j+1][i])[2]+v,max(decode(dp[j][i+1]))+v)*base**3
print(max(decode(dp[-1][-1])))

Submission status: Time Limit Exceeded

Solution code:
import sys, math
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from itertools import combinations, permutations, product
from heapq import heappush, heappop
from functools import lru_cache
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 1000000007
sys.setrecursionlimit(1000000)

R, C, K = rl()
I = [[0]*(C+2) for _ in range(R+2)]
for i in range(K):
	r, c, v = rl()
	I[r][c] = v

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

for i in range(R+1):
	for j in range(C+1):
		for m in range(4):
			ni, nj = i, j+1
			dp[ni][nj][m] = max(dp[ni][nj][m], dp[i][j][m])
			if m < 3:
				dp[ni][nj][m+1] = max(dp[ni][nj][m+1], dp[i][j][m]+I[ni][nj])
			ni, nj = i+1, j
			dp[ni][nj][0] = max(dp[ni][nj][0], dp[i][j][m])
			dp[ni][nj][1] = max(dp[ni][nj][1], dp[i][j][m]+I[ni][nj])
ans = 0
for m in range(4):
	ans = max(ans, dp[R][C][m])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

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

#############
# Functions #
#############

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


#####Shorten#####
def DD(arg): return defaultdict(arg)

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

######Combination######
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

######Factorization######
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

#####MakeDivisors######
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

#####MakePrimes######
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

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

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

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

#####ChangeBase#####
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]

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

#############
# Main Code #
#############
base = 10**20
def decode(x):
  a = x%base
  x //= base
  b = x%base
  x //= base
  c = x%base
  x //= base
  d = x%base
  return [a,b,c,d]

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 for i in range(C+1)] for j in range(R+1)]
for j in range(R):
  for i in range(C):
    v = data[j][i] 
    if v == 0:
      dp[j+1][i+1] += max(decode(dp[j+1][i])[0],max(decode(dp[j][i+1])))
      dp[j+1][i+1] += max(decode(dp[j+1][i])[1],max(decode(dp[j][i+1])))*base
      dp[j+1][i+1] += max(decode(dp[j+1][i])[2],max(decode(dp[j][i+1])))*base**2
      dp[j+1][i+1] += max(decode(dp[j+1][i])[3],max(decode(dp[j][i+1])))*base**3
    else:
      dp[j+1][i+1] += max(decode(dp[j+1][i])[0],max(decode(dp[j][i+1])))
      dp[j+1][i+1] += max(decode(dp[j+1][i])[1],decode(dp[j+1][i])[0]+v,max(decode(dp[j][i+1]))+v)*base
      dp[j+1][i+1] += max(decode(dp[j+1][i])[2],decode(dp[j+1][i])[1]+v,max(decode(dp[j][i+1]))+v)*base**2
      dp[j+1][i+1] += max(decode(dp[j+1][i])[3],decode(dp[j+1][i])[2]+v,max(decode(dp[j][i+1]))+v)*base**3
print(max(decode(dp[-1][-1])))

Submission status: Time Limit Exceeded

Solution code:
R,C,K = map(int,input().split())
dp = [[[0 for l in range(4)] 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):
		dp[i][j][0] = max(dp[i][j][0], dp[i-1][j][0], dp[i-1][j][1], dp[i-1][j][2], dp[i-1][j][3])
		dp[i][j][3] = max(dp[i][j-1][3], dp[i][j][2]+vl[i][j], dp[i][j-1][2]+vl[i][j])
		dp[i][j][2] = max(dp[i][j-1][2], dp[i][j][1]+vl[i][j], dp[i][j-1][1]+vl[i][j])
		dp[i][j][1] = max(dp[i][j-1][1], dp[i][j][0]+vl[i][j], dp[i][j-1][0]+vl[i][j])

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

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin,setrecursionlimit
setrecursionlimit(1000000)
input=stdin.readline
n,m,ss=map(int,input().split())
mat=[[0]*m for i in range(n)]
for i in range(ss):
    x,y,v=map(int,input().split())
    mat[x-1][y-1]+=v
dp=[[[-1]*4 for i in range(m)] for j in range(n)]
l=3
def dfs(x,y,k):
    if x<0 or y<0 or x>=n or y>=m:
        return 0
    if dp[x][y][k]!=-1:
        return dp[x][y][k]
    if k>0:
        dp[x][y][k]=max(mat[x][y]+dfs(x+1,y,l),mat[x][y]+dfs(x,y+1,k-1),dfs(x,y+1,k),dfs(x+1,y,l))
    else:
        dp[x][y][k]=max(dfs(x+1,y,l),dfs(x,y+1,k))
    return dp[x][y][k]

print(dfs(0,0,l))