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:
# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
import sys
def main():
    input = sys.stdin.readline
    R, C, K = map(int, input().split())
    M = [[0] * C for _ in range(R)]
    for _ in range(K):
        r, c, v = map(int, input().split())
        M[r - 1][c - 1] = v

    # dp[i][j][k]=(i,j)にいてその行でk個取得済みの場合の価値の最大値
    dp = [[[-1] * 4 for _ in range(C)] for __ in range(R)]
    dp[0][0][0] = 0
    dp[0][0][1] = M[0][0]
    for i in range(R):
        for j in range(C):
            now = dp[i][j]
            for k in range(4):
                nowk = now[k]
                if nowk < 0: continue
                # 下へ
                if i < R - 1:
                    down = dp[i + 1][j]
                    # 取らない
                    down[0] = max(down[0], nowk)
                    # 取る
                    v = M[i + 1][j]
                    if v > 0:
                        down[1] = max(down[1], nowk + v)
                # 右へ
                if j < C - 1:
                    right = dp[i][j + 1]
                    # 取らない
                    right[k] = max(right[k], nowk)
                    # 取る
                    v = M[i][j + 1]
                    if v > 0 and k < 3:
                        right[k + 1] = max(right[k + 1], nowk + v)
    print(max(dp[R - 1][C - 1]))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    
    r, c, k = map(int, input().split())
    tizu = [[0 for _ in range(c)] for _ in range(r)]
    for _ in range(k):
        rr, cc, v = map(int, input().split())
        tizu[rr - 1][cc - 1] = v
        
    dp = [[0, 0, 0, 0] for _ in range(c)]
    dp[0][1] = tizu[0][0]
    
    for i in range(r):
        for j in range(c):
            v = tizu[i][j]
            if i != 0:
                tmp = max(dp[j])
                dp[j][0] = tmp
                dp[j][1] = tmp + v
                dp[j][2] = 0
                dp[j][3] = 0
            if j != 0:
                tmp0 = dp[j - 1][0]
                tmp1 = dp[j - 1][1]
                tmp2 = dp[j - 1][2]
                dp[j][0] = max(dp[j][0], tmp0)
                dp[j][1] = max(dp[j][1], tmp1, tmp0 + v)
                dp[j][2] = max(tmp2, tmp1 + v)
                dp[j][3] = max(dp[j - 1][3], tmp2 + v)
    print(max(dp[-1]))
    
main()

Submission status: Time Limit Exceeded

Solution code:
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):
    i, j, v = map(int, input().split())
    items[i][j] = v

# dp[i][j][m] = (i行j列時点で、i行でm個のitemを取得している時の価値の最大値)
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 m in range(4):
            dp[i][j][m] = max(dp[i][j][m], max(dp[i - 1][j]), dp[i][j - 1][m])
        for m in reversed(range(3)):
            dp[i][j][m + 1] = max(dp[i][j][m + 1], dp[i][j][m] + items[i][j])

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

Submission status: Time Limit Exceeded

Solution code:
# dp[r][c][p] := 位置r, cに到着し、該当行で拾ったアイテムがp個の時の、最大価値
# r = 0〜R, c = 0〜C, p = 0〜3

R, C, k = list(map(int, input().split()))
items = [list(map(int, input().split())) for _ in range(k)]

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

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

for item in items:
    item_values[item[0]][item[1]] = item[2]

for r in range(1, R+1):
    for c in range(1, C+1):
        value_here = item_values[r][c]

        if value_here == 0:
            dp[r][c][0] = max(
                dp[r][c-1][0],
                max(dp[r-1][c])
            )
            dp[r][c][1] = dp[r][c-1][1]
            dp[r][c][2] = dp[r][c-1][2]
            dp[r][c][3] = dp[r][c-1][3]
        
        else:
            dp[r][c][0] = max(
                dp[r][c-1][0],
                max(dp[r-1][c])
            )
            dp[r][c][1] = max([
                dp[r][c-1][1],
                dp[r][c-1][0] + value_here,
                max(dp[r-1][c]) + value_here
            ])

            dp[r][c][2] = max(dp[r][c-1][2], dp[r][c-1][1] + value_here)
            dp[r][c][3] = max(dp[r][c-1][3], dp[r][c-1][2] + value_here)
            
print(max(dp[R][C]))

# print(dp)

Submission status: Time Limit Exceeded

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

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

# dp[i][j][m] = (i行j列時点で、i行でm個のitemを取得している時の価値の最大値)
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 m in range(4):
            dp[i][j][m] = max(dp[i][j][m], max(dp[i - 1][j]), dp[i][j - 1][m])
        for m in reversed(range(3)):
            dp[i][j][m + 1] = max(dp[i][j][m + 1], dp[i][j][m] + items[i][j])

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

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
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, input().split()))
    d[(a,b)] = c

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

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(max(dp[R][C]))

Submission status: Time Limit Exceeded

Solution code:
R,C,K = map(int,input().split())
V = [[0 for c in range(C+1)] for r in range(R+1)]
for i in range(K):
	r,c,v = map(int,input().split())
	V[r][c] = v
dp = [[[0 for i in range(4)] for j in range(C+1)] for k in range(R+1)]
for r in range(1, R+1):
	for c in range(1, C+1):
		v = V[r][c]
		under_val = max(dp[r-1][c])
		dp[r][c][0] = max(under_val, dp[r][c-1][0])
		if v > 0:
			dp[r][c][1] = max(under_val + v, dp[r][c-1][0] + v, dp[r][c-1][1])
			dp[r][c][2] = max(dp[r][c-1][1] + v, dp[r][c-1][2])
			dp[r][c][3] = max(dp[r][c-1][2] + v, dp[r][c-1][3])
		else:
			dp[r][c][1] = dp[r][c-1][1]
			dp[r][c][2] = dp[r][c-1][2]
			dp[r][c][3] = dp[r][c-1][3]
print(max(dp[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    
    r, c, k = map(int, input().split())
    tizu = [[0 for _ in range(c)] for _ in range(r)]
    for _ in range(k):
        rr, cc, v = map(int, input().split())
        tizu[rr - 1][cc - 1] = v
        
    dp = [[0, 0, 0, 0] for _ in range(c)]
    dp[0][1] = tizu[0][0]
    
    for i in range(r):
        for j in range(c):
            if i != 0:
                tmp = max(dp[j])
                dp[j][0] = tmp
                dp[j][1] = tmp + tizu[i][j]
                dp[j][2] = 0
                dp[j][3] = 0
            if j != 0:
                dp[j][0] = max(dp[j][0], dp[j - 1][0])
                dp[j][1] = max(dp[j][1], dp[j - 1][1], dp[j - 1][0] + tizu[i][j])
                dp[j][2] = max(dp[j - 1][2], dp[j - 1][1] + tizu[i][j])
                dp[j][3] = max(dp[j - 1][3], dp[j - 1][2] + tizu[i][j])
    print(max(dp[-1]))
    
main()

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
"""
    info = dict()
for r,item in rcv.items():
  item.sort(key=lambda x:x[0])
  if len(item) < 2:
    info[r] = [[item[0][0],item[0][0],item[0][1]]]
  elif len(item) < 3:
    info[r] = [[item[0][0],item[1][0],item[0][1]+item[1][1]]]
  else:
    ret=list()
    for i in range(len(item)-2):
      ret.append([item[i][0],item[i+2][0],sum([item[j][1] for j in range(i,i+3)])])

# info: 各行でmax3つのアイテムをとるときの列区間とその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):
  for c in range(1,C+1):
    if r*c == 1:
      continue
    for i in range(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:
R,C,K = map(int,input().split())
V = [[0 for c in range(C+1)] for r in range(R+1)]
for i in range(K):
	r,c,v = map(int,input().split())
	V[r][c] = v
dp = [[[0 for i in range(4)] for j in range(C+1)] for k in range(R+1)]
for r in range(1, R+1):
	for c in range(1, C+1):
		v = V[r][c]
		under_val = max(dp[r-1][c])
		dp[r][c][0] = max(under_val, dp[r][c-1][0])
		dp[r][c][1] = max(under_val + v, dp[r][c-1][0] + v, dp[r][c-1][1])
		dp[r][c][2] = max(dp[r][c-1][1] + v, dp[r][c-1][2])
		dp[r][c][3] = max(dp[r][c-1][2] + v, dp[r][c-1][3])
print(max(dp[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
(r,c,_),*d = [list(map(int, s.split())) for s in open(0)]

v = dict()
for dd in d:
    v[dd[0]-1, dd[1]-1] = dd[2]

dp = np.zeros([r,4], dtype=int)
for i in range(c):
    for j in range(r):
        if j > 0:
            dp[j][0] = max(dp[j][0], max(dp[j-1]))
        dp[j][1:] = np.maximum(dp[j][1:], dp[j][:-1] + v.get((j,i), 0))
print(np.max(dp))

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline

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

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

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

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

    # print(f'{dp=}')
    ans = max(dp[-1][-1])
    print(ans)


if __name__ == '__main__':
    main()

# def binary_search(*, ok, ng, func):
#     while abs(ok - ng) > 1:
#         mid = (ok + ng) // 2
#         if func(mid):
#             ok = mid
#         else:
#             ng = mid
#     return ok

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.buffer.readline
R,C,K = map(int,input().split())
goods = [[-1]*(C+1) for _ in range(R+1)]
INF = 10**16
for i in range(K):
    ri,ci,vi = map(int,input().split())
    goods[ri][ci] = vi
DP = [[[-INF,-INF,-INF,-INF] for _ in range(C+1)] for _ in range(R+1)]
DP[1][1][0] = 0
if goods[1][1] != -1:
    DP[1][1][1] = goods[1][1]
for j in range(1,C):
    DP[1][j+1][0] = 0
    if goods[1][j+1] != -1:
        DP[1][j+1][1] = max(DP[1][j][1],DP[1][j][0]+goods[1][j+1])
        DP[1][j+1][2] = max(DP[1][j][2],DP[1][j][1]+goods[1][j+1])
        DP[1][j+1][3] = max(DP[1][j][3],DP[1][j][2]+goods[1][j+1])
    else:
        DP[1][j+1][1] = DP[1][j][1]
        DP[1][j+1][2] = DP[1][j][2]
        DP[1][j+1][3] = DP[1][j][3]
for i in range(1,R):
    DP[i+1][1][0] = max(DP[i][1])
    if goods[i+1][1] != -1:
        DP[i+1][1][1] = DP[i+1][1][0] + goods[i+1][1]
for i in range(2,R+1):
    for j in range(2,C+1):
        DP[i][j][0] = max(max(DP[i-1][j]),DP[i][j-1][0])
        if goods[i][j] != -1:
            DP[i][j][1] = max(DP[i][j][0]+goods[i][j],DP[i][j-1][1])
            DP[i][j][2] = max(DP[i][j-1][2],DP[i][j-1][1]+goods[i][j])
            DP[i][j][3] = max(DP[i][j-1][3],DP[i][j-1][2]+goods[i][j])
        else:
            DP[i][j][1] = DP[i][j-1][1]
            DP[i][j][2] = DP[i][j-1][2]
            DP[i][j][3] = DP[i][j-1][3]
print(max(DP[R][C]))

Submission status: Time Limit Exceeded

Solution code:
import sys

r, c, k = map(int, sys.stdin.buffer.readline().split())
items = [[0] * (c + 1) for _ in range(r + 1)]
rcv = map(int, sys.stdin.buffer.read().split())
for r_, c_, v in zip(rcv, rcv, rcv):
    items[r_][c_] = 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):
        up = dp[i - 1][j][3]
        for w in range(4):
            dp[i][j][w] = max(dp[i][j - 1][w], up)
        v = items[i][j]
        if v == 0:
            continue
        for w in range(2, -1, -1):
            dp[i][j][w + 1] = max(dp[i][j][w + 1], dp[i][j][w] + v)

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

Submission status: Time Limit Exceeded

Solution code:
# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
import sys
def main(R, C, K, M):
    # dp[i][j][k]=(i,j)にいてその行でk個取得済みの場合の価値の最大値
    dp = [[[-1] * 4 for _ in range(C)] for __ in range(R)]
    dp[0][0][0] = 0
    dp[0][0][1] = M[0][0]
    for i in range(R):
        for j in range(C):
            now = dp[i][j]
            for k in range(4):
                if now[k] < 0: continue
                # 下へ
                if i < R - 1:
                    # 取らない
                    dp[i + 1][j][0] = max(dp[i + 1][j][0], now[k])
                    # 取る
                    v = M[i + 1][j]
                    if v > 0:
                        dp[i + 1][j][1] = max(dp[i + 1][j][1], now[k] + v)
                # 右へ
                if j < C - 1:
                    # 取らない
                    dp[i][j + 1][k] = max(dp[i][j + 1][k], now[k])
                    # 取る
                    v = M[i][j + 1]
                    if v > 0 and k < 3:
                        dp[i][j + 1][k + 1] = max(dp[i][j + 1][k + 1], now[k] + v)
    print(max(dp[R - 1][C - 1]))
    # for d in dp:
    #    print(d)

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

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:
        dp[i*w+j][0] = max(dp[i*w+j][0], max(dp[(i-1)*w+j]))
        dp[i*w+j][1] = max(dp[i*w+j][1], max(dp[(i-1)*w+j])+G[i*w+j])
  ans = max(dp[U-1])
  print(ans)
if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:

from sys import stdin

R,C,K = map(int,stdin.readline().split())

lis = [[0] * (C+1) for i in range(R+1)]

for i in range(K):

    r,c,v = map(int,stdin.readline().split())
    r -= 1
    c -= 1
    lis[r][c] += v

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

for j in range(C+1):
    for i in range(R+1):
        for k in range(4):

            #取る
            if k != 3:

                #右に行く
                if j != C:
                    dp[j+1][i][k+1] = max(dp[j+1][i][k+1],dp[j][i][k] + lis[i][j])
                #下に行く
                if i != R:
                    dp[j][i+1][0] = max(dp[j][i+1][0] , dp[j][i][k] + lis[i][j])

            #取らない

            #右に行く
            if j != C:
                dp[j+1][i][k] = max(dp[j+1][i][k],dp[j][i][k])
            #下に行く
            if i != R:
                dp[j][i+1][0] = max(dp[j][i+1][0] , dp[j][i][k])

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

Submission status: Time Limit Exceeded

Solution code:
# dp[r][c][p] := 位置r, cに到着し、該当行で拾ったアイテムがp個の時の、最大価値
# r = 0〜R, c = 0〜C, p = 0〜3

R, C, k = list(map(int, input().split()))
items = [list(map(int, input().split())) for _ in range(k)]

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

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

for item in items:
    item_values[item[0]][item[1]] = item[2]

for r in range(R+1):
    for c in range(C+1):
        value_r_plus = item_values[r+1][c]
        value_c_plus = item_values[r][c+1]
        now = dp[r][c]
        max_now = max(now)

        if value_r_plus > 0:
            # 上方にいどうしてアイテムを拾う
            dp[r+1][c][1] = max(dp[r+1][c][1], max_now + value_r_plus)
        
        # 上方に移動してアイテムを拾わない
        # dp[r+1][c][0] = max(dp[r+1][c][0], now[0], now[1], now[2], now[3])
        dp[r+1][c][0] = max(dp[r+1][c][0], max_now)

        # 右に移動してアイテムを拾わない
        dp[r][c+1][0] = max(dp[r][c+1][0], now[0])
        dp[r][c+1][1] = max(dp[r][c+1][1], now[1])
        dp[r][c+1][2] = max(dp[r][c+1][2], now[2])
        dp[r][c+1][3] = max(dp[r][c+1][3], now[3])

        if value_c_plus > 0:
            # 右に移動してアイテムを拾う
            dp[r][c+1][1] = max(dp[r][c+1][1], now[0] + value_c_plus)
            dp[r][c+1][2] = max(dp[r][c+1][2], now[1] + value_c_plus)
            dp[r][c+1][3] = max(dp[r][c+1][3], now[2] + value_c_plus)
            
print(max(dp[R][C]))

# print(dp)

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    
    r, c, k = map(int, input().split())
    tizu = [[0 for _ in range(c)] for _ in range(r)]
    for _ in range(k):
        rr, cc, v = map(int, input().split())
        tizu[rr - 1][cc - 1] = v
        
    dp = [[[0, 0, 0, 0] for _ in range(c)] for _ in range(r)]
    dp[0][0][1] = tizu[0][0]
    
    for i in range(r):
        for j in range(c):
            if i != 0:
                tmp = max(dp[i - 1][j])
                dp[i][j][0] = tmp
                dp[i][j][1] = tmp + tizu[i][j]
            if 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], dp[i][j - 1][1], dp[i][j - 1][0] + tizu[i][j])
                dp[i][j][2] = max(dp[i][j - 1][2], dp[i][j - 1][1] + tizu[i][j])
                dp[i][j][3] = max(dp[i][j - 1][3], dp[i][j - 1][2] + tizu[i][j])
    print(max(dp[-1][-1]))
    
main()

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(500000)
def input():
    return sys.stdin.readline()[:-1]

def smax(i,j):
    if i>j:
        return i
    else:
        return j

def smax2(L):
    return smax(smax(L[0],L[1]),smax(L[2],L[3]))

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

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

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

    for i in range(R):
        for j in range(C):
            if i!=0 and j!=0:
                DP[i][j][0] = smax(smax2(DP[i-1][j]), DP[i][j-1][0])
                DP[i][j][1] = smax(DP[i][j-1][0] + D[i][j], smax(DP[i][j-1][1],smax2(DP[i-1][j])+D[i][j]))
                DP[i][j][2] = smax(DP[i][j-1][1] + D[i][j], DP[i][j-1][2])
                DP[i][j][3] = smax(DP[i][j-1][2] + D[i][j], DP[i][j-1][3])
            elif i!=0 and j==0:
                DP[i][j][0] = smax2(DP[i-1][j])
                DP[i][j][1] = smax2(DP[i-1][j])+D[i][j]
            elif i==0 and j!=0:
                DP[i][j][0] = DP[i][j-1][0]
                DP[i][j][1] = smax(DP[i][j-1][0] + D[i][j], DP[i][j-1][1])
                DP[i][j][2] = smax(DP[i][j-1][1] + D[i][j], DP[i][j-1][2])
                DP[i][j][3] = smax(DP[i][j-1][2] + D[i][j], DP[i][j-1][3])
            else:
                DP[i][j][0] = 0
                DP[i][j][1] = D[i][j]

    print(smax2(DP[R-1][C-1]))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def Rtest(T):
    case,err=0,0
    for i in range(T):
        inp=INP()
        a1,ls=naive(*inp)
        a2=solve(*inp)
        if a1!=a2:
            print((a1,a2),inp)
            err+=1
        case+=1
    print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in R(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**9)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()


show_flg=False
show_flg=True

ans=0

h,w,k=LI()
v=[[0]*(w+1) for i in range(h+1)]
for i in rep(k):
    a,b,x=LI()
    v[a][b]=x

dp=[[[0]*4 for i in range(w+1)] for i in range(h+1)]

for i in range(1,h+1):
    for j in range(1,w+1):
        up_max=max(dp[i-1][j][x]for x in range(4))
        dp[i][j][0]=up_max
        if v[i][j]!=0:
            dp[i][j][1]=max(dp[i][j][1],up_max+v[i][j])
        dp[i][j][0]=max(dp[i][j][0],dp[i][j-1][0])
        for x in range(1,4)[::-1]:
            dp[i][j][x]=max(dp[i][j][x],dp[i][j-1][x],dp[i][j-1][x-1]+v[i][j])
            

ans=max(dp[h][w])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

d = [(1,0),(0,1)]
def solve():
    h,w,k = LI()
    s = [[0]*w for i in range(h)]
    for _ in range(k):
        y,x,v = LI()
        y -= 1
        x -= 1
        s[y][x] = v
    dp = [[[-float("inf")]*4 for _ in range(w)] for _ in range(h)]
    dp[0][0][0] = 0
    sc = s[0][0]
    if sc != 0:
        dp[0][0][1] = sc
    for y in range(h):
        for x in range(w):
            for n in range(4):
                dyx = dp[y][x][n]
                for dy,dx in d:
                    ny,nx = y+dy,x+dx
                    if dy:
                        nn = 0
                    else:
                        nn = n
                    if 0 <= ny < h and 0 <= nx < w:
                        if dp[ny][nx][nn] < dyx:
                            dp[ny][nx][nn] = dyx
                        if nn < 3:
                            nsc = s[ny][nx]
                            if nsc != 0:
                                nn += 1
                                ndp = dyx+nsc
                                if dp[ny][nx][nn] < ndp:
                                    dp[ny][nx][nn] = ndp
    print(max(dp[-1][-1]))
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

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

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

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

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

dp[0][0][1] = values[0][0]
    
for i in range(R):
    for j in range(C):
        for k in range(4):
            if i + 1 < R:
                dp[i+1][j][0] = max(dp[i+1][j][0], dp[i][j][k])
                dp[i+1][j][1] = max(dp[i+1][j][1], dp[i][j][k] + values[i+1][j])
            if j + 1 < C:
                dp[i][j+1][k] = max(dp[i][j+1][k], dp[i][j][k])
                if k + 1 <= 3:
                    dp[i][j+1][k+1] = max(dp[i][j+1][k+1], dp[i][j][k] + values[i][j+1])
                

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

Submission status: Time Limit Exceeded

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

X = [[[0] * 4 for _ in range(C + 1)] for _ in range(R + 1)]
for i in range(1, R + 1):
    Xi = X[i]
    Xi1 = X[i-1]
    Vi = V[i]
    for j in range(1, C + 1):
        Vij = Vi[j]
        Xij = Xi[j]
        Xij1 = Xi[j-1]
        Xij[0] = max(max(Xi1[j]), Xij1[0])
        Xij[1] = max(Xij[0] + Vij, Xij1[1])
        Xij[2] = max(Xij1[1] + Vij, Xij1[2])
        Xij[3] = max(Xij1[2] + Vij, Xij1[3])

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

Submission status: Time Limit Exceeded

Solution code:
r, c, k = map(int, input().split())
a = [[0] * c for _ in range(r)]
for _ in range(k):
    d, b, v = map(int, input().split())
    a[d - 1][b - 1] = v
dp = [[[0] * 4 for _ in range(c)] for _ in range(r)]
dp[0][0][1] = a[0][0]
for i in range(r):
    for j in range(c):
        for k in range(3):
            if i > 0:
                dp[i][j][1] = max(dp[i][j][1],
                                  dp[i - 1][j][k] + a[i][j])
                dp[i][j][0] = max(dp[i][j][0], dp[i - 1][j][k])
            if j > 0:
                dp[i][j][k + 1] = max(dp[i][j][k + 1],
                                      dp[i][j - 1][k] + a[i][j])
                dp[i][j][k] = max(dp[i][j][k], dp[i][j - 1][k])
        if i > 0:
            dp[i][j][0] = max(dp[i][j][0], dp[i - 1][j][3])
            dp[i][j][1] = max(dp[i][j][1], dp[i - 1][j][3] + a[i][j])
        if j > 0:
            dp[i][j][3] = max(dp[i][j][3], dp[i][j - 1][3])
print(max(dp[r - 1][c - 1]))

Submission status: Time Limit Exceeded

Solution code:
r, c, k = map(int, input().split())
grid = [[0] * c for _ in range(r)]
dp = [[[0] * 4 for _ in range(c+1)] for _ in range(r+1)]

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

for y in range(1, r+1):
    for x in range(1, c+1):
        v = grid[y-1][x-1]
        prev_y_max = max(dp[y-1][x][:])
        dp[y][x][0] = max(prev_y_max, dp[y][x-1][0])
        if v != 0:
            dp[y][x][1] = max(prev_y_max + v, dp[y][x-1][0] + v, dp[y][x-1][1])
            dp[y][x][2] = max(dp[y][x-1][1] + v, dp[y][x-1][2])
            dp[y][x][3] = max(dp[y][x-1][2] + v, dp[y][x-1][3])
        else:
            for i in range(1, 4):
                dp[y][x][i] = dp[y][x-1][i]
print(max(dp[r][c]))