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:
R, C, K = map(int, input().split())
g = [[-float('inf')]*C for _ in range(R)]
for i in range(K):
    r, c, k = map(int, input().split())
    r -= 1
    c -= 1
    g[r][c] = k

dp = [[[0]*4 for _ in range(C+1)] for _ in range(R+1)]
for r in range(R):
    for c in range(C):
        # k[0..3] = 0個拾っている状態から3個拾っている状態
        # indexが大きいほど、小さいアイテムとなるので、小さいものから更新していく
        for k in range(2, -1, -1):
            dp[r][c][k+1] = max(
                dp[r][c][k+1],
                dp[r][c][k]+g[r][c]
            )

        for k in range(4):
            dp[r+1][c][0] = max(dp[r+1][c][0], dp[r][c][k])
            dp[r][c+1][k] = max(dp[r][c+1][k], dp[r][c][k])
print(max(dp[R-1][C-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
r,c,k = map(int,input().split())
d = {}
for i in range(k):
    x,y,v = map(int,input().split())
    d[(x-1,y-1)] = v

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

for i in range(r):
    for j in range(c):
        M = max(dp[i][j+1])
        if (i,j) in d:
            v = d[(i,j)]
            dp[i+1][j+1][0] = max(M,dp[i+1][j][0])
            dp[i+1][j+1][1] = max(M+v,dp[i+1][j][0]+v,dp[i+1][j][1])
            dp[i+1][j+1][2] = max(dp[i+1][j][1]+v,dp[i+1][j][2])
            dp[i+1][j+1][3] = max(dp[i+1][j][2]+v,dp[i+1][j][3])
        else:
            dp[i+1][j+1][0] = max(M,dp[i+1][j][0])
            dp[i+1][j+1][1] = dp[i+1][j][1]
            dp[i+1][j+1][2] = dp[i+1][j][2]
            dp[i+1][j+1][3] = dp[i+1][j][3]
print(max(dp[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.buffer.readline
r, c, k = map(int, input().split())


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

for _ in range(k):
    d, e, f = map(int, input().split())
    graph[d - 1][e - 1] = f


# dijkstra
infi = 10 ** 10
money = [[[-infi] * (4) for _ in range(c)] for _ in range(r)]
money[0][0][0] = 0
for i in range(r):
    for j in range(c):
        for t in range(4):
            m = money[i][j][t]
            delta = graph[i][j]
            if i < r - 1:
                ni = i + 1
                nj = j
                nt = 0
                money[ni][nj][nt] = max(money[ni][nj][nt], m)
                if t < 3:
                    money[ni][nj][nt] = max(money[ni][nj][nt], m + delta)

            if j < c - 1:
                ni = i
                nj = j + 1
                nt = t
                money[ni][nj][nt] = max(money[ni][nj][nt], m)
                if t < 3:
                    nt = t + 1
                    money[ni][nj][nt] = max(money[ni][nj][nt], m + delta)


if graph[r - 1][c - 1] > 0:
    for t in range(3):
        money[r - 1][c - 1][t] += graph[r - 1][c - 1]
ans = max(money[r - 1][c - 1])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
r,c,k = map(int,input().split())
l = [[0]*c for i in range(r)]

for i in range(k):
    x,y,v = map(int,input().split())
    l[x-1][y-1] = v

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

for i in range(r):
    for j in range(c):
        M = max(dp[i][j+1])
        if l[i][j] > 0:
            v = l[i][j]
            dp[i+1][j+1][0] = max(M,dp[i+1][j][0])
            dp[i+1][j+1][1] = max(M+v,dp[i+1][j][0]+v,dp[i+1][j][1])
            dp[i+1][j+1][2] = max(dp[i+1][j][1]+v,dp[i+1][j][2])
            dp[i+1][j+1][3] = max(dp[i+1][j][2]+v,dp[i+1][j][3])
        else:
            dp[i+1][j+1][0] = max(M,dp[i+1][j][0])
            dp[i+1][j+1][1] = dp[i+1][j][1]
            dp[i+1][j+1][2] = dp[i+1][j][2]
            dp[i+1][j+1][3] = dp[i+1][j][3]
print(max(dp[-1][-1]))

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)]
dp0 = dp[0]; dp1 = dp[1]; dp2 = dp[2]; dp3 = dp[3]
dp[0][0] = 0
for j in range(C):
    for i in range(R):
        for k in range(4):
            ij = i * C + j
            ij1 = ij + 1
            i1j = ij + C
            item = field[i][j]
            # Use
            if item and k < 3:
                dp[k+1][ij1] = max(dp[k+1][ij1], dp[k][ij] + item) 
                dp0[i1j] = max(dp0[i1j], dp[k][ij] + item) 
            # No use down
            dp0[i1j] = max(dp0[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:
r,c,k = map(int,input().split())
l = [[0]*c for i in range(r)]

for i in range(k):
    x,y,v = map(int,input().split())
    l[x-1][y-1] = v

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

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

Submission status: Time Limit Exceeded

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

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]
    if r < R - 1:
      point[r+1][c][0] = maps[r+1][c] + max(a, b, d)      
    if c < C - 1:
      x = maps[r][c+1]
      y = point[r][c+1]
      y[0] = max(y[0], x, a)
      y[1] = max(a + x, b)
      y[2] = max(b + x, d)
      point[r][c+1] = y

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

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

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)]
    maxx = [[0 for _ in range(C)] for i 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]
        maxx[i][0] = max(dp[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])
        maxx[0][j] = max(dp[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):
        j_1 = 0
        for j in range(1,C):
            dp[i][j][0] = max(maxx[i-1][j], 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])
                j_1 = j
            else:
                for k in range(1,4):
                    dp[i][j][k] = dp[i][j-1][k]
            maxx[i][j] = max(dp[i][j])
                # maxx[i][j] = max(maxx[i][j-1], dp[i][j][0])

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


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

# fast read all
inn = 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,inn[0].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 t in range(1,nrows+1):
        grid.append(list(map(int,inn[t].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, 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):
		d = dp[i][j]
		for ni, nj in [[i+1, j], [i, j+1]]:
			nd = dp[ni][nj]
			v = I[ni][nj]
			for m in range(4):
				if i == ni:
					nd[m] = max(nd[m], d[m])
					if m < 3:
						nd[m+1] = max(nd[m+1], d[m]+v)
				else:
					nd[0] = max(nd[0], d[m])
					nd[1] = max(nd[1], d[m] + v)
ans = 0
for m in range(4):
	ans = max(ans, dp[R][C][m])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import time
s1 = time.time()
*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)])

# print(time.time() - s1)
mx = 0
for row in range(1, R + 1):
    for col in range(1, C + 1):
        level = 0
        while level < 4:
            dp[1][row][col] = max(dp[1][row][col], dp[level][row - 1][col] + grid[row - 1][col - 1])
            dp[0][row][col] = max(dp[0][row][col], dp[level][row - 1][col])
            level += 1
        level = 1
        while level < 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])
            level += 1

# print(time.time() - s1)
print(mx)

Submission status: Time Limit Exceeded

Solution code:
# pypy
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
from collections import defaultdict

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

dp = [[[0]*4 for c in range(C)] for r in range(2)]
dp[0][0][1] = rc2v[(0, 0)]

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

for r in range(1, R):
  rr = r % 2
  dp[rr][0][0] = max(dp[rr-1][0])
  dp[rr][0][1] = dp[rr][0][0] + rc2v[(r, 0)]
  for c in range(1, C):
    temp_max = max(dp[rr-1][c])
    dp[rr][c][1] = max(dp[rr][c-1][1], max(dp[rr][c-1][0], temp_max)+rc2v[(r, c)])
    for k in range(2, 4):
      dp[rr][c][k] = max(dp[rr][c-1][k], dp[rr][c-1][k-1]+rc2v[(r, c)])
    
if R % 2:
  print(max(dp[0][-1]))
else:
  print(max(dp[-1][-1]))

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],max(dp[i-1][j]))
        v=grid[i][j]
        if v==0:
            for k in range(4):
                dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k])
        if v!=0:
            dp[i][j][0]=max(dp[i][j][0],dp[i][j-1][0])
            dp[i][j][1]=max(dp[i][j][1],max(dp[i-1][j])+v)
            for k in range(1,4):
                dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k-1]+v,dp[i][j-1][k])

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

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

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:
      x = maps[r][c+1]
      y = point[r][c+1]
      y[0] = max(y[0], x, a)
      y[1] = max(y[1], a + x, b)
      y[2] = max(y[2], b + x, d)
      point[r][c+1] = y

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
R, C, K = map(int, input().split())
item = {}
for _ in range(K):
    r, c, v = map(int, input().split())
    item[(r, c)] = v

dp = [[[0] * 4 for _ in range(3010)] for _ in range(3010)]
for r in range(1, R+1):
    for c in range(1, C+1):
        prer = max(dp[r-1][c])
        dp[r][c][0] = max(prer, dp[r][c-1][0])
        dp[r][c][1] = max(prer, dp[r][c-1][1])
        dp[r][c][2] = max(prer, dp[r][c-1][2])
        dp[r][c][3] = max(prer, dp[r][c-1][3])
        if item.get((r, c)):
            dp[r][c][1] = max(dp[r][c][1], max(prer, dp[r][c-1][0]) + item[(r,c)])
            dp[r][c][2] = max(dp[r][c][2], max(prer, dp[r][c-1][1]) + item[(r,c)])
            dp[r][c][3] = max(dp[r][c][3], max(prer, dp[r][c-1][2]) + item[(r,c)])

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import sys
from numba import njit, i8

input = sys.stdin.readline

R, C, K = map(int, input().split())
table = [[0] * (C + 1) for _ in range(R + 1)]
for _ in range(K):
    r, c, v = map(int, input().split())
    table[r][c] = v
table = np.array(table, dtype=np.int64)


@njit((i8, i8, i8[:, :]), cache=True)
def solve(R, C, table):
    dp = np.zeros((R + 1, C + 1, 4), dtype=np.int64)
    for r in range(1, R + 1):
        for c in range(1, C + 1):
            m = dp[r - 1, c].max()
            dp[r, c] = np.maximum(m, dp[r, c - 1])
            if table[r][c] is not None:
                dp[r, c, 1:] = np.maximum(dp[r, c, 1:],
                                          np.maximum(m, dp[r, c - 1, :-1]) + table[r][c])

    return dp[-1, -1].max()


print(solve(R, C, table))

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 = ij + 1
            i1j = ij + C
            item = field[i][j]
            # Use
            if item and k < 3:
                dp[k+1][ij1] = max(dp[k+1][ij1], dp[k][ij] + item) 
                dp[0][i1j] = max(dp[0][i1j], dp[k][ij] + item) 
            # 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

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def solve():
    dp = [[[-inf] * 4 for _ in range(w)] for _ in range(h)]
    dp[0][0][0] = 0
    for i in range(h):
        for j in range(w):
            for c in range(4):
                pre = dp[i][j][c]
                if pre == -inf: continue
                if i + 1 < h: dp[i + 1][j][0] = max(dp[i + 1][j][0], pre)
                if j + 1 < w: dp[i][j + 1][c] = max(dp[i][j + 1][c], pre)
                if aa[i][j]:
                    if c < 3 and i + 1 < h: dp[i + 1][j][0] = max(dp[i + 1][j][0], pre + aa[i][j])
                    if c < 3 and j + 1 < w: dp[i][j + 1][c + 1] = max(dp[i][j + 1][c + 1], pre + aa[i][j])

    ans = -inf
    for c in range(4):
        if c == 3: ans = max(ans, dp[h - 1][w - 1][c])
        else: ans = max(ans, dp[h - 1][w - 1][c] + aa[h - 1][w - 1])
    print(ans)

inf=10**16
h,w,k=MI()
aa=[[0]*w for _ in range(h)]
for _ in range(k):
    i,j,v=MI()
    aa[i-1][j-1]=v
solve()

Submission status: Time Limit Exceeded

Solution code:
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
	dp=[[[0]*4 for i in range(C+1)]for j in range(R+1)]
	for i in range(1,R+1):
		for j in range(1,C+1):
			for k in range(4):
				t=lis[i-1][j-1]
				dp[i][j][k]=max(dp[i-1][j][k],dp[i][j][k])
				dp[i][j][k]=max(dp[i][j-1][k],dp[i][j][k])
				if t!=0:
					
					dp[i][j][1]=max(dp[i][j][1],dp[i-1][j][k]+t)
					if k>0:
						dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k-1]+t)
	print(max(dp[-1][-1]))
if __name__ == '__main__':
	main()

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],max(dp[i-1][j]))
        if grid[i][j]==0:
            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][0]=max(dp[i][j][0],dp[i][j-1][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],dp[i][j-1][k])

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

Submission status: Time Limit Exceeded

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

dp = [[[0] * 4 for _ in range(3010)] for _ in range(3010)]
for r in range(1, R+1):
    for c in range(1, C+1):
        prer = max(dp[r-1][c])
        dp[r][c][0] = max(prer, dp[r][c-1][0])
        dp[r][c][1] = max(prer, dp[r][c-1][1])
        dp[r][c][2] = max(prer, dp[r][c-1][2])
        dp[r][c][3] = max(prer, dp[r][c-1][3])
        if item[r][c] > 0:
            dp[r][c][1] = max(dp[r][c][1], max(prer, dp[r][c-1][0]) + item[r][c])
            dp[r][c][2] = max(dp[r][c][2], max(prer, dp[r][c-1][1]) + item[r][c])
            dp[r][c][3] = max(dp[r][c][3], max(prer, dp[r][c-1][2]) + item[r][c])

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

Submission status: Time Limit Exceeded

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

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[r][c][i] = max(dp[r+1][c][3], dp[r][c+1][i])
            else:
                dp[r][c][i] = max(dp[r + 1][c][3]+v, dp[r][c + 1][i], dp[r][c + 1][i-1] + v)

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

Submission status: Time Limit Exceeded

Solution code:
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
dp=[[[0]*4 for i in range(C+1)]for j in range(R+1)]
for i in range(1,R+1):
	for j in range(1,C+1):
		for k in range(4):
			t=lis[i-1][j-1]
			dp[i][j][k]=max(dp[i-1][j][k],dp[i][j][k])
			dp[i][j][k]=max(dp[i][j-1][k],dp[i][j][k])
			if t!=0:
				
				dp[i][j][1]=max(dp[i][j][1],dp[i-1][j][k]+t)
				if k>0:
					dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k-1]+t)
print(max(dp[-1][-1]))