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:
# -*- 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 #
#############

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(700000)

def s_in():
    return input()

def n_in():
    return int(input())

def l_in():
    return list(map(int, input().split()))

r,c,k=l_in()

item = {}

for _ in range(k):
    i,j,v = l_in()
    item[(i,j)] = v


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

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

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

Submission status: Time Limit Exceeded

Solution code:
from numba import njit

R, C, K = map(int, input().split())
rcvs = [tuple(map(int, input().split())) for _ in range(K)]

rcvs.sort(key = lambda t: t[1] * 30000 + t[0])

@njit(cache = True)
def solve(rcvs):
    dp = [[0] * (R+1) for _ in range(4)]
    index = 0
    for c in range(C+1):
        while index < K and rcvs[index][1] == c:
            x, _, v = rcvs[index]
            if dp[3][x] < dp[2][x] + v:
                dp[3][x] = dp[2][x] + v
            if dp[2][x] < dp[1][x] + v:
                dp[2][x] = dp[1][x] + v
            if dp[1][x] < dp[0][x] + v:
                dp[1][x] = dp[0][x] + v
            index += 1
            for r in range(x, R):
                if dp[0][r+1] < max(dp[0][r], dp[1][r], dp[2][r], dp[3][r]):
                    dp[0][r+1] = max(dp[0][r], dp[1][r], dp[2][r], dp[3][r])
                else:
                    break
            #print(dp)   
        
    ans = max([max(row) for row in dp])
    return ans

print(solve(rcvs))

Submission status: Time Limit Exceeded

Solution code:
r,c,k = map(int, input().split())
rcv = [list(map(int, input().split())) for i in range(k)]
d = dict()
for rr,cc,vv in rcv:
    d[(rr-1,cc-1)] = vv

DP_now = [[0]*4 for i in range(c)]
DP_prev = [[0]*4 for i in range(c)]

for i in range(r):
    for j in range(c):
        max_top = max(DP_prev[j]) if i!=0 else 0
        if (i,j) in d:
            v = d[(i,j)]
            DP_now[j][0] = max_top
            DP_now[j][1] = max_top + v
            for k in range(4):
                if j != 0:
                    if DP_now[j][k] < DP_now[j-1][k]:
                        DP_now[j][k] = DP_now[j-1][k]
                    if k!=0 and DP_now[j][k] < DP_now[j-1][k-1] + v:
                        DP_now[j][k] =  DP_now[j-1][k-1] + v
        else:
            DP_now[j][0] = max_top
            if j>0:
                DP_now[j] = DP_now[j-1][:]
            if DP_now[j][0] < max_top:
                DP_now[j][0] = max_top
    DP_prev = DP_now
    DP_now = [[0]*4 for i in range(c)]
ans = max(DP_prev[-1])
print(ans)

Submission status: Time Limit Exceeded

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

R, C, K = mapint()
dp = [[[0]*4 for _ in range(C)] for _ in range(R)]
from collections import defaultdict
dic = defaultdict(int)
for _ in range(K):
    r, c, v = mapint()
    dic[(r-1, c-1)] = v

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
*data, = map(int, sys.stdin.read().split()[::-1])
def inp():
    global data
    return data.pop()
R, C, k = inp(), inp(), inp()
grid = [[0] * C for _ in range(R)]

for _ in range(k):
    ri, ci, v = inp(), inp(), inp()
    grid[ri - 1][ci - 1] = v


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


mx = 0
for row in range(1, R + 1):
    for col in range(1, C + 1):
        for level in range(4):
            dp[0][row][col] = max(dp[0][row][col], dp[level][row - 1][col])
            dp[1][row][col] = max(dp[1][row][col], dp[level][row - 1][col] + grid[row - 1][col - 1])
        for level in range(1, 4):
            dp[level][row][col] = max(
                dp[level][row][col],
                dp[level - 1][row][col - 1] + grid[row - 1][col - 1],
                dp[level][row][col - 1],
            )
            mx = max(mx, dp[level][row][col])

print(mx)

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict

# available on Google, not available on Codeforces
# import numpy as np
# import scipy


def solve(items,R,C):  # fix inputs here
    console("----- solving ------")
    console(R,C)

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

    for r,c,v in items:
        grid[r-1][c-1] = v

    # console(np.array(grid))  # PLEASE SILENCE
    console("\n\n")

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

    if grid[0][0] > 0:
        dp[0][0][1] = dp[0][0][0] + grid[0][0]

    for i in range(1,R):
        dp[i][0][0] = max(dp[i-1][0][0], dp[i-1][0][1])
        if grid[i][0] > 0:
            dp[i][0][1] = dp[i][0][0] + grid[i][0]

    for j in range(1,C):
        for k in range(1,4):
            dp[0][j][k] = max(dp[0][j-1][k], dp[0][j-1][k-1] + grid[0][j])

    # console(np.array(dp)[:,:,0])  # PLEASE SILENCE
    # console(np.array(dp)[:,0,:])  # PLEASE SILENCE
    # console(np.array(dp)[0,:,:])  # PLEASE SILENCE
    # console(np.array(dp))  # PLEASE SILENCE
    # console("\n\nPost")

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

    # console(np.array(dp)[:,:,0])  # PLEASE SILENCE
    # console(np.array(dp)[:,:,1])  # PLEASE SILENCE
    # console(np.array(dp)[:,:,2])  # PLEASE SILENCE
    # console(np.array(dp)[:,:,3])  # PLEASE SILENCE
    # console(np.array(dp))  # PLEASE SILENCE

    # return a string (i.e. not a list or matrix)
    return max(dp[R-1][C-1][k] for k in range(4))


def console(*args):  # the judge will not read these print statement
    print('\033[36m', *args, '\033[0m', file=sys.stderr)
    return

# fast read all
# sys.stdin.readlines()

for case_num in [1]:
    # read line as a string
    # strr = input()

    # read line as an integer
    # k = int(input())
    
    # read one line and parse each word as a string
    # lst = input().split()

    # read one line and parse each word as an integer
    r,c,nrows = list(map(int,input().split()))

    # read matrix and parse as integers (after reading read nrows)
    # lst = list(map(int,input().split()))
    # nrows = lst[0]  # index containing information, please change
    grid = []
    for _ in range(nrows):
        grid.append(list(map(int,input().split())))

    res = solve(grid,r,c)  # please change
    
    # Google - case number required
    # print("Case #{}: {}".format(case_num+1, res))

    # Codeforces - no case number required
    print(res)

Submission status: Time Limit Exceeded

Solution code:
import sys
def input(itr=iter(sys.stdin.readlines())):  # pylint: disable= redefined-builtin
    return next(itr).rstrip('\n\r')
###############################################################################

#region bcf
# code section by Barry Fam
#
# pylint: disable= reimported
#region mapping2d.py
import copy

class Mapping2D:
    """
    A convenience class for accessing a 2d array with map-like methods

    Mapping2D(n: int, m: int) -> new empty mapping of size n x m
    Mapping2D(iterable of iterables) -> initialized

    >>> x = Mapping2D([[9, 8, 7], [6, 5, 4]])
    >>> x[1,1]
    5
    >>> (0,1) in x
    True

    >>> del x[1,0]
    >>> (1,0) in x
    False
    >>> x[1,0]
    Traceback (most recent call last):
        ...
    KeyError: (1, 0)
    >>> x.get((1,0), 'empty')
    'empty'

    >>> x[0,0] = 42
    >>> list(x.items())
    [((0, 0), 42), ((0, 1), 8), ((0, 2), 7), ((1, 1), 5), ((1, 2), 4)]

    >>> y = x.copy()
    >>> x == y
    True

    Also has methods for treating the array as "walkable" with adjacent cells connected:

    >>> x.inbounds((99,99))
    False

    >>> list(x.neighbors((1,1)))  # note empty cells are included
    [(0, 1), (1, 0), (1, 2)]
    """

    def __init__(self, *arg):
        self.none = object()

        try:
            iterable = iter(arg[0])
            self.a = [list(row) for row in iterable]
            self.dim = len(self.a), len(self.a[0])
            assert all(len(row) == self.dim[1] for row in self.a)
            self.len = self.dim[0] * self.dim[1]

        except TypeError:
            self.dim = arg
            self.a = [[self.none]*self.dim[1] for _ in range(self.dim[0])]
            self.len = 0

    def __repr__(self):
        return "Mapping2D({})".format(repr(self.a))

    def __len__(self):
        return self.len

    def inbounds(self, u):
        return 0 <= u[0] < self.dim[0] and 0 <= u[1] < self.dim[1]

    def __contains__(self, u):
        return self.inbounds(u) and self.a[u[0]][u[1]] is not self.none

    def __getitem__(self, u):
        if u not in self: raise KeyError(u)
        return self.a[u[0]][u[1]]

    def __setitem__(self, u, x):
        if not self.inbounds(u): raise KeyError(u)
        if u not in self: self.len += 1
        self.a[u[0]][u[1]] = x

    def __delitem__(self, u):
        if not self.inbounds(u): raise KeyError(u)
        if u in self:
            self.len -= 1
            self.a[u[0]][u[1]] = self.none

    def get(self, u, default=None):
        if u in self: return self[u]
        else: return default

    def update(self, iterable):
        for u, x in iterable:
            self[u] = x

    def clear(self):
        self.__init__(self.dim[0], self.dim[1])

    def items(self):
        for i in range(self.dim[0]):
            for j in range(self.dim[1]):
                x = self.a[i][j]
                if x is self.none: continue
                yield (i, j), x

    def keys(self):
        return (k for k, _ in self.items())

    def values(self):
        return (v for _, v in self.items())

    def __iter__(self):
        return self.keys()

    def __eq__(self, other):
        return isinstance(other, Mapping2D) and all(x == y for x, y in zip(self.items(), other.items()))

    def copy(self):
        return copy.deepcopy(self)

    @staticmethod
    def _dmoves(u):
        D_PAD = ((-1,0), (0,-1), (0,1), (1,0))
        return ((u[0]+d[0], u[1]+d[1]) for d in D_PAD)

    def neighbors(self, u):
        return (v for v in self._dmoves(u) if self.inbounds(v))


# if __name__ == "__main__":
if False:  # pylint: disable= using-constant-test
    import doctest
    doctest.testmod()

#endregion mapping2d.py
#endregion bcf
###############################################################################

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

dp = Mapping2D(R+1, C+1)
for i in range(R+1): dp[i, 0] = (0, 0, 0, 0)
for j in range(C+1): dp[0, j] = (0, 0, 0, 0)

for i in range(1, R+1):
    for j in range(1, C+1):
        item = items[i-1, j-1]

        dp[i, j] = [0]*4
        dp[i, j][0] = max(dp[i-1, j])
        dp[i, j][1] = dp[i, j][0] + item

        for k in range(3):
            dp[i, j][k+1] = max(dp[i, j][k+1], dp[i, j-1][k] + item)

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

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

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
# import numpy as np
sys.setrecursionlimit(10**6)
# INF =  float("inf")
INF = 10**18
import bisect
import statistics
mod = 10**9+7
# mod = 998244353

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

d = defaultdict(int)
for i in range(K):
    a, b, c = list(map(int, stdin.readline().split()))
    d[(a,b)] = c

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

# dp = np.zeros((R+1, C+1, 4))

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


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

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
import bisect
import copy
import heapq
import itertools
import math
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


class V:
    def __init__(self, f, v=None):
        self.f = f
        self.v = v
 
    def __str__(self):
        return str(self.v)
 
    def ud(self, n):
        if n is None:
            return

        if self.v is None:
            self.v = n
            return
        self.v = self.f(self.v, n) 


def main():
    R, C, K = read_values()
    V = [0] * (R * C)
    for _ in range(K):
        r, c, v = read_values()
        r -= 1
        c -= 1
        V[r * C + c] = v
    
    dp = [[0, 0, 0, 0] for _ in range(R * C)]
    for i in range(R * C):
        r = i // C
        c = i % C
        if c + 1 < C:
            # not take
            for k in range(4):
                dp[i + 1][k] = max(dp[i + 1][k], dp[i][k])

            # take 
            for k in range(3):
                dp[i + 1][k + 1] = max(dp[i + 1][k + 1], dp[i][k] + V[i])

        # next r
        if r + 1 < R:
            for k in range(4):
                dp[i + C][0] = max(dp[i + C][0], dp[i][k] + (V[i] if k < 3 else 0))

    print(max(k + (V[-1] if i  < 3 else 0) for i, k in enumerate(dp[-1])))


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
r, c, k = map(int,input().split())
grid = [[0] * c for i in range(r)]
for _ in range(k):
    R, C, V = map(int,input().split())
    grid[R - 1][C - 1] = V
    
dp = [[[0, 0, 0, 0] for i in range(c)] for i in range(r)]
#dp[i][j]:= (i, j)に来た時点での考えられる最大スコア

dp[0][0][1] = max(grid[0][0], 0)
for i in range(r):
    for j in range(c):
        if 0 <= j + 1 < c:
            #横移動は拾える数に制約がある
            temp = grid[i][j + 1]            
            for k in range(3):
                #入れる場合
                dp[i][j + 1][k + 1] = max(dp[i][j][k + 1],dp[i][j + 1][k + 1], dp[i][j][k] + temp)
                
        if 0 <= i + 1 < r:
            temp = grid[i + 1][j]
            temp_pre = max(dp[i][j])
            
            dp[i + 1][j][0] = max(temp_pre, dp[i + 1][j][0])
            if temp > 0:
                dp[i + 1][j][1] = max(temp_pre + temp, dp[i + 1][j][1])
        
        
            
print(max(dp[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:

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

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

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):
        for k in range(4):
            # Horizontal
            dp[i][j][k] = max(dp[i][j][k], dp[i][j - 1][k])

            # Vertical
            dp[i][j][0] = max(dp[i][j][0], dp[i - 1][j][k])

        for k in reversed(range(4)):
            # Pick up items
            if (i, j) in items and k < 3:
                dp[i][j][k + 1] = max(
                    dp[i][j][k + 1], dp[i][j][k] + items[(i, j)])

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

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
def main():
    r,c,k=map(int,input().split())
    v=dict()
    for _ in range(k):
        ri,ci,a=map(int,input().split())
        ri-=1
        ci-=1
        v[(ri,ci)]=a
    dp=[[[0]*4 for _ in range(c)] for i in range(r)]
    #print(dp)
    if (0,0) in v:
        if v[(0,0)]>0:
            dp[0][0][1]=v[(0,0)]
    for i in range(r):
        for j in range(c):
            if i>0:
                if (i,j) in v:
                    if v[(i,j)]>0:
                        for k in range(min(3,j+1)+1):
                            dp[i][j][1]=max(dp[i][j][1],dp[i-1][j][k]+v[(i,j)])
                for k in range(4):
                    dp[i][j][k]=max(dp[i][j][k],dp[i-1][j][k])
            if j>0:
                if (i,j) in v:
                    if v[(i,j)]>0:
                        for k in range(min(3,j+1)+1):
                            if k>0:
                                dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k-1]+v[(i,j)])
                for k in range(4):
                    dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k])
    #print(dp)
    print(max(dp[r-1][c-1]))
if __name__=="__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
R, C, K = map(int, input().split())
V = [[[] for _ in range(C)] for _ in range(R)]
for _ in range(K):
  r, c, v = map(int, input().split())
  V[r-1][c-1].append(v)
M = [[[0, 0, 0, 0] for _ in range(C)] for _ in range(R)]
# M[r][c][count in column (c)]
for r in range(R):
  for c in range(C):
    V[r][c].sort(reverse=True)
    candidates = [[0] for _ in range(4)]
    #print(candidates)
    for n_pick in range(1 + min(3, len(V[r][c]))):
      candidates[n_pick].append(sum(V[r][c][:n_pick]))
      if r > 0:
        for n_prev in range(4):
          #print('R++', r, c, n_pick, n_prev)
          if M[r-1][c][n_prev] > 0 or n_prev == 0:
            candidates[n_pick].append(
              M[r-1][c][n_prev] + sum(V[r][c][:n_pick]))
      if c > 0:
        for n_prev in range(4 - n_pick):
          #print('C++', r, c, n_pick, n_prev)
          if  M[r][c-1][n_prev]  > 0 or n_prev == 0:
            candidates[n_prev+n_pick].append(
              M[r][c-1][n_prev] + sum(V[r][c][:n_pick]))
    #print(candidates)
    #print(r, c, candidates, M)
    for i in range(4):
      M[r][c][i] = max(candidates[i])
    #print(r, c, M)
#print(V, M)
print(max(M[R-1][C-1]))

Submission status: Time Limit Exceeded

Solution code:
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
# dp: 各場所までの合計の最大値
dp = [[[0 for _ in range(4)] for _ in range(C+1)] for _ in range(R+1)]
if rcv[1][1]>0:
  dp[1][1][1] = rcv[1][1]
#print(dp[1][1][1])
for r in range(1,R+1):
  cntmax=1
  for c in range(1,C+1):
    if rcv[r][c] > 0:
      cntmax += 1
    if r*c == 1:
      continue
    for i in range(min(cntmax,4)):
      candi=list()
      if r > 1 and i==0:  #うえからおりてくる、とらない(i=0)
        candi.extend(dp[r-1][c])
      if r > 1 and i==1 and rcv[r][c]>0:  #うえからおりてくる、とる(i=1)
        candi.extend([dp[r-1][c][j]+rcv[r][c] for j in range(4)])
      if c > 1: # ひだりから、とらない(i維持)
        candi.append(dp[r][c-1][i])
        if 0 < i and rcv[r][c]>0:  # ひだりから、とる(i-1から移行)
          candi.append(dp[r][c-1][i-1]+rcv[r][c])
      if len(candi) == 0:
        continue
      dp[r][c][i] = max(candi)
      #print(r,c,i,dp[r][c][i])
print(max(dp[R][C]))

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 = {}
for i in range(K):
	r, c, v = rl()
	I[(r-1, c-1)] = v

#dist = [[[-float('inf')]*3 for _ in range(C)] for _ in range(R)]
dist = defaultdict(lambda: -float('inf'))
dist[(0, 0, 0, 0)] = 0
heap = []
heappush(heap, (-0, (0, 0, 0, 0)))
ans = 0
while heap:
	d, n = heappop(heap)
	d = -d
	r, c, m, f = n
	#print('rcm', r, c, m, d, f)
	if r == R-1 and c == C-1:
		#print(dist)
		if m < 3 and f == 0:
			if (r, c) in I:
				d += I[(r,c)]
		ans = max(ans, d)
		#break
		continue
	if dist[n] != d:
		continue
	for i, j, k in [[0, 1, m], [1, 0, 0]]:
		ni, nj = r+i, c+j
		if ni >= R or nj >= C: continue
		nn = (ni, nj, k, 0)
		if dist[nn] < d:
			dist[nn] = d
			heappush(heap, (-d, nn))
	if m < 3 and f == 0:
		if (r, c) in I:
			nn = (r, c, m+1, 1)
			nd = d + I[(r,c)]
			if dist[nn] < nd:
				dist[nn] = nd
				heappush(heap, (-nd, nn))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def calc(r, c):
    return (r * (10 ** 4)) + c


row, column, k = map(int, input().split())

my_d = dict()

for _ in range(k):
    r, c, v = map(int, input().split())
    if calc(r-1, c-1) in my_d:
        my_d[calc(r-1, c-1)].append(v)
    else:
        my_d[calc(r-1, c-1)] = [v]

# for item in my_d:
#    my_d[item].sort()

dp = [[[0 for _ in range(4)] for _ in range(column)] for _ in range(row)]

for i in range(row):
    for j in range(column):
        for kosu in range(4):
            if kosu == 0:
                dp[i][j][0] = 0 if i == 0 else max(dp[i-1][j])
            elif kosu == 1:
                cand1 = 0 if i == 0 else max(dp[i-1][j])
                cand2 = 0 if j == 0 else dp[i][j-1][1]
                cand3 = 0 if calc(i, j) not in my_d else my_d[calc(i, j)][-1]
                dp[i][j][1] = max(cand1 + cand3, cand2)
            elif kosu == 2:
                cand1 = 0 if i == 0 else max(dp[i-1][j])
                cand2 = 0 if j == 0 else dp[i][j-1][1]
                cand3 = 0 if calc(i, j) not in my_d else my_d[calc(i, j)][-1]
                cand4 = 0 if i == 0 else max(dp[i-1][j])
                cand5 = 0 if j == 0 else dp[i][j-1][2]
                cand6 = 0 if (calc(i, j) not in my_d or len(
                    my_d[calc(i, j)]) < 2) else sum(my_d[calc(i, j)][-2:])
                dp[i][j][2] = max(cand5, cand6 + cand4, cand2 + cand3)
            elif kosu == 3:
                cand1 = 0 if i == 0 else max(dp[i-1][j])
                cand2 = 0 if j == 0 else dp[i][j-1][1]
                cand3 = 0 if calc(i, j) not in my_d else my_d[calc(i, j)][-1]
                cand4 = 0 if i == 0 else max(dp[i-1][j])
                cand5 = 0 if j == 0 else dp[i][j-1][2]
                cand6 = 0 if (calc(i, j) not in my_d or len(
                    my_d[calc(i, j)]) < 2) else sum(my_d[calc(i, j)][-2:])
                cand7 = 0 if i == 0 else max(dp[i-1][j])
                cand8 = 0 if j == 0 else dp[i][j-1][3]
                cand9 = 0 if (calc(i, j) not in my_d or len(
                    my_d[calc(i, j)]) < 3) else sum(my_d[calc(i, j)][-3:])
                dp[i][j][3] = max(cand8, cand7+cand9, cand5+cand3, cand2+cand6)

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

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

def main():
  h, w, k = map(int, input().split())
  U = h*w
  G = [0]*U
  for _ in range(k):
    r, c, v = map(int, input().split())
    r -= 1
    c -= 1
    G[r*w+c] = v
  dp = [[0]*4 for _ in range(U)]
  dp[0][0] = 0
  dp[0][1] = G[0]
  for i in range(h):
    for j in range(w):
      if j:
        dp[i*w+j][0] = dp[i*w+j-1][0]
        for k in range(1, 4):
          dp[i*w+j][k] = max(dp[i*w+j][k], dp[i*w+j-1][k-1]+G[i*w+j], dp[i*w+j-1][k])
      if i:
        temp = max(dp[(i-1)*w+j])
        dp[i*w+j][0] = max(dp[i*w+j][0], temp)
        dp[i*w+j][1] = max(dp[i*w+j][1], temp+G[i*w+j])
  ans = max(dp[U-1])
  print(ans)
if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
R, C, k = map(int, input().split())
grid = [[0] * C for _ in range(R)]

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


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


mx = 0
for row in range(1, R + 1):
    for col in range(1, C + 1):
        for level in range(4):
            dp[0][row][col] = max(dp[0][row][col], dp[level][row - 1][col])
            dp[1][row][col] = max(dp[1][row][col], dp[level][row - 1][col] + grid[row - 1][col - 1])
        for level in range(1, 4):
            dp[level][row][col] = max(
                dp[level][row][col],
                dp[level - 1][row][col - 1] + grid[row - 1][col - 1],
                dp[level][row][col - 1],
            )
            mx = max(mx, dp[level][row][col])

print(mx)