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: Accepted

Solution code:
import numba
from numba import jit
import numpy as np

#(i,j)→(i+1,j)のように動くときはアイテムを入手できる回数がリセットされる
#dp[列][今、何個アイテムを取ったか]でdpテーブルを作る
@jit
def main(r, c):
  dp = np.zeros((c+1, 4), np.int64)
  for i in range(r):
    new_dp = np.zeros((c+1, 4), np.int64)
    for j in range(4):
      new_dp[:,0] = np.maximum(new_dp[:,0], dp[:,j])
    dp = new_dp
    for k in range(c):
      for l in range(2, -1, -1):
        dp[k,l+1] = max(dp[k,l+1], dp[k,l]+item_map[i,k])
      for m in range(1,4):
        dp[k+1,m] = max(dp[k+1,m], dp[k,m])
  return max(dp[c-1,:])

R, C, K = map(int, input().split())
item_lis = list(list(map(int, input().split())) for i in range(K))
item_map = np.zeros((R, C), np.int64)
for i,j,k in item_lis:
  item_map[i-1,j-1] = k

print(main(R, C))

Submission status: Accepted

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

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

dp0 = [[0]*C for _ in range(R)]
dp1 = [[0]*C for _ in range(R)]
dp2 = [[0]*C for _ in range(R)]
dp3 = [[0]*C for _ in range(R)]

for i in range(R):
  for j in range(C):
    if dp1[i][j] < dp0[i][j]+board[i][j]:
      dp1[i][j] = dp0[i][j]+board[i][j]
    if j>0:
      if dp0[i][j] < dp0[i][j-1]:
        dp0[i][j] = dp0[i][j-1]
      if dp1[i][j] < dp1[i][j-1]:
        dp1[i][j] = dp1[i][j-1]
      if dp2[i][j] < dp2[i][j-1]:
        dp2[i][j] = dp2[i][j-1]
      if dp3[i][j] < dp3[i][j-1]:
        dp3[i][j] = dp3[i][j-1]
      if dp1[i][j] < dp0[i][j-1]+board[i][j]:
        dp1[i][j] = dp0[i][j-1]+board[i][j]
      if dp2[i][j] < dp1[i][j-1]+board[i][j]:
        dp2[i][j] = dp1[i][j-1]+board[i][j]
      if dp3[i][j] < dp2[i][j-1]+board[i][j]:
        dp3[i][j] = dp2[i][j-1]+board[i][j]
    if i>0:
      if dp0[i][j] < dp0[i-1][j]:
        dp0[i][j] = dp0[i-1][j]
      if dp0[i][j] < dp1[i-1][j]:
        dp0[i][j] = dp1[i-1][j]
      if dp0[i][j] < dp2[i-1][j]:
        dp0[i][j] = dp2[i-1][j]
      if dp0[i][j] < dp3[i-1][j]:
        dp0[i][j] = dp3[i-1][j]
      if dp1[i][j] < dp0[i-1][j]+board[i][j]:
        dp1[i][j] = dp0[i-1][j]+board[i][j]
      if dp1[i][j] < dp1[i-1][j]+board[i][j]:
        dp1[i][j] = dp1[i-1][j]+board[i][j]
      if dp1[i][j] < dp2[i-1][j]+board[i][j]:
        dp1[i][j] = dp2[i-1][j]+board[i][j]
      if dp1[i][j] < dp3[i-1][j]+board[i][j]:
        dp1[i][j] = dp3[i-1][j]+board[i][j]
print(max(dp0[-1][-1],dp1[-1][-1],dp2[-1][-1],dp3[-1][-1]))

Submission status: Accepted

Solution code:
import numba
from numba import jit
import numpy as np
  
@jit
def main(r, c):
  dp = np.zeros((c+1, 4), np.int64)
  for i in range(r):
    new_dp = np.zeros((c+1, 4), np.int64)
    for j in range(4):
      new_dp[:,0] = np.maximum(new_dp[:,0], dp[:,j])
    dp = new_dp
    for k in range(c):
      for l in range(2, -1, -1):
        dp[k,l+1] = max(dp[k,l+1], dp[k,l]+item_map[i,k])
      for m in range(1,4):
        dp[k+1,m] = max(dp[k+1,m], dp[k,m])
  return max(dp[c-1,:])


R, C, K = map(int, input().split())
item_lis = list(list(map(int, input().split())) for i in range(K))
item_map = np.zeros((R, C), np.int64)
for i,j,k in item_lis:
  item_map[i-1,j-1] = k

print(main(R, C))

Submission status: Accepted

Solution code:
f=lambda:map(int,input().split())
g=range
R,C,K=f()
a=[[0]*(R+1) for _ in g(C+1)]
for _ in g(K):
  r,c,v=f()
  a[c][r]=v
dp=[[0]*4 for _ in g(R+1)]
for i in g(1,C+1):
  for j in g(1,R+1):
    t=a[i][j]
    if t:
      for k in [3,2,1]:
        dp[j][k]=max(dp[j][k],dp[j][k-1]+t)
      dp[j][1]=max(dp[j][1],max(dp[j-1])+t)
    dp[j][0]=max(dp[j][0],max(dp[j-1]))
print(max(dp[R]))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

R,C,K=map(int,input().split())
V=[[0]*C for _ in range(R)]
for i in range(K):
    r,c,v=map(int,input().split())
    r-=1
    c-=1
    V[r][c]=v
dp=[[0]*C for _ in range(4)]
for y in range(R):
    for x in range(C):
        for i in range(2,-1,-1):
            dp[i+1][x]=max(dp[i+1][x],dp[i][x]+V[y][x])
        if x<C-1:
            for i in range(3,-1,-1):
                dp[i][x+1]=max(dp[i][x+1],dp[i][x])
    if y+1<R:
        MAX=0
        for x in range(C):
            for i in range(4):
                MAX=max(MAX,dp[i][x])
                dp[i][x]=0
            dp[0][x]=MAX
print(max(dp[0][-1],dp[1][-1],dp[2][-1],dp[3][-1]))

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    R, C, K, *RCV = map(int, read().split())

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

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

    print(dp[C])

    return


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

for i in range(1, C+1):
    for j in range(1, R+1):
        temp = max(dp0[i][j-1], dp1[i][j-1])
        temp = max(dp2[i][j-1], temp)
        temp = max(dp3[i][j-1], temp)
        dp0[i][j] = max(temp, dp0[i-1][j])
        if val[i][j]>0:
            dp1[i][j] = max(dp0[i-1][j]+val[i][j], dp1[i-1][j],temp+val[i][j])
            dp2[i][j] = max(dp1[i-1][j]+val[i][j], dp2[i-1][j])
            dp3[i][j] = max(dp2[i-1][j]+val[i][j], dp3[i-1][j])
        else:
            dp1[i][j] = dp1[i-1][j]
            dp2[i][j] = dp2[i-1][j]
            dp3[i][j] = dp3[i-1][j]

print(max(dp0[-1][-1], dp1[-1][-1], dp2[-1][-1],dp3[-1][-1]))

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

R,C,K = LI()
r,c,v = LIR(K,3)

def index(i,j,k):
    return k*C*R + i*C + j

a = [[0]*C for _ in range(R)]
for i in range(K):
    a[r[i]-1][c[i]-1] = v[i]

dp = [0]*(4*C*R)
dp[index(0,0,1)] = a[0][0]

for i in range(R):
    for j in range(C):
        if i == j == 0:
            continue
        upper_max = 0
        if i >= 1:
            for k in range(4):
                upper_max = max(upper_max,dp[index(i-1,j,k)])
        for k in range(4):
            val1 = 0
            val2 = 0
            val3 = 0
            val4 = 0
            if j >= 1:
                val1 = dp[index(i,j-1,k)]
            if k == 0 and i >= 1:
                val2 = upper_max
            if a[i][j] != 0:
                if k == 1 and i >= 1:
                    val3 = upper_max + a[i][j]
                if k >= 1 and j >= 1:
                    val4 = dp[index(i,j-1,k-1)] + a[i][j]
            dp[index(i,j,k)] = max(val1,val2,val3,val4)

ans = 0
for k in range(4):
    ans = max(ans,dp[index(R-1,C-1,k)])

print(ans)

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    R, C, K, *RCV = map(int, read().split())

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

    dp = [0] * (C + 1)
    for i in range(R):
        value = [0] * 4
        for j in range(C):
            for k in range(4):
                if value[k] < dp[j + 1]:
                    value[k] = dp[j + 1]
                else:
                    break
            if item[i][j] > 0:
                for k in range(2, -1, -1):
                    if value[k + 1] < value[k] + item[i][j]:
                        value[k + 1] = value[k] + item[i][j]
            dp[j + 1] = value[3]

    print(dp[C])

    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def exit(*argv, **kwarg):
    print(*argv, **kwarg)
    sys.exit()


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def a_int(): return int(read())


def ints(): return list(map(int, read().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque


'''
dp[i][j]...(0,0)からスタートして(i,j)に到達する経路のなかでの最大の価値
dp[i][j]=max(dp[i][j-1],dp[i-1][j]) + v[i][j]


dp[i][j][k] ... (0,0)からスタートして(i,j)に到達する経路のなかでi行目ですでにk(以下)個選んでいるときの最大の価値

遷移は、i,jのvを拾うときと拾わないときのmax
dp[i][j][k] = max(dp[i][j-1][k-1]+V[i,j], dp[i][j-1][k]
                  ) #k個のままのほうが価値が高いかk-1から拾ったほうが価値が高いか

上からの遷移 # 拾うか拾わないかでこうかな
dp[i][j][0]=max(dp[i][j-1][0],max_k(dp[i-1][j]))
dp[i][j][1]=max(dp[i][j-1][0],max_k(dp[i-1][j][k])+V[i][j])
'''

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

# dp = [[[0] * 4 for _ in ra(C)] for _ in ra(R)]
dp0 = [[0] * C for _ in ra(R)]
dp1 = [[0] * C for _ in ra(R)]
dp2 = [[0] * C for _ in ra(R)]
dp3 = [[0] * C for _ in ra(R)]

# dp[0][0][0] = 0
dp1[0][0] = V[0][0]
dp2[0][0] = V[0][0]
dp3[0][0] = V[0][0]

for j in ra(1, C):
    dp1[0][j] = max(dp1[0][j - 1], dp0[0][j - 1] + V[0][j])
    dp2[0][j] = max(dp2[0][j - 1], dp1[0][j - 1] + V[0][j])
    dp3[0][j] = max(dp3[0][j - 1], dp2[0][j - 1] + V[0][j])

for i in ra(1, R):
    dp0[i][0] = dp1[i - 1][0]
    dp1[i][0] = dp0[i][0] + V[i][0]
    dp2[i][0] = dp0[i][0] + V[i][0]
    dp3[i][0] = dp0[i][0] + V[i][0]


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

        dp0[i][j] = max(dp0[i][j - 1],  # 左
                        ma)  # 上

        if ma > max(dp3[i][j - 1], dp2[i][j - 1], dp1[i][j - 1]):  # 上から採用
            dp1[i][j] = ma + V[i][j]
            dp2[i][j] = ma + V[i][j]
            dp3[i][j] = ma + V[i][j]
        else:  # 横から採用
            dp1[i][j] = max(dp0[i][j - 1] + V[i][j],  # 左から来て拾う
                            dp1[i][j - 1],  # 拾わないほうが大きい場合もある
                            ma + V[i][j])  # 上から来て拾う
            dp2[i][j] = max(dp1[i][j - 1] + V[i][j], dp2[i][j - 1])
            dp3[i][j] = max(dp2[i][j - 1] + V[i][j], dp3[i][j - 1])


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

# print(*values, sep='\n')
# print(*dp3, sep='\n')

# dp2 = [[-1] * C for _ in ra(R)]
# for i in ra(R):
#     for j in ra(C):
#         dp2[i][j] = max(dp[i][j])
# print(*dp2, sep='\n')

Submission status: Accepted

Solution code:
r,c,k = map(int,input().split())
lst = [[0]*c for _ in range(r)]
for i in range(k):
    a,b,v = map(int,input().split())
    lst[a-1][b-1] = v
dp0 = [[0]*c for _ in range(r)]
dp1 = [[0]*c for _ in range(r)]
dp2 = [[0]*c for _ in range(r)]
dp3 = [[0]*c for _ in range(r)]
dp1[0][0] = lst[0][0]

for i in range(r):
    for j in range(c):
        s = max(dp0[i][j], dp1[i][j], dp2[i][j], dp3[i][j])
        x,y = i+1,j
        if x < r:
            dp0[x][y] = max(dp0[x][y], s)
            if lst[x][y]:
                dp1[x][y] = max(dp1[x][y], s+lst[x][y])
        x,y = i,j+1
        if y < c:
            dp3[x][y] = max(dp3[i][j], dp3[x][y])
            if lst[x][y]:
                dp3[x][y] = max(dp2[i][j]+lst[x][y], dp3[x][y])
            
            dp2[x][y] = max(dp2[x][y], dp2[i][j])
            if lst[x][y]:
                dp2[x][y] = max(dp2[x][y], dp1[i][j]+lst[x][y])
            
            dp1[x][y] = max(dp1[x][y], dp1[i][j])
            if lst[x][y]:
                dp1[x][y] = max(dp1[x][y], dp0[i][j]+lst[x][y])
            
            dp0[x][y] = max(dp0[x][y], dp0[i][j])
print(max(dp0[-1][-1], dp1[-1][-1], dp2[-1][-1], dp3[-1][-1]))

Submission status: Accepted

Solution code:
import numpy as np
from numba import njit


@njit
def solve():
    dp = np.zeros((R + 1, C + 1, 4), dtype=np.int64)
    for i in range(1, R + 1):
        for j in range(1, C + 1):
            for k in range(4):
                dp[i][j][k] = max(dp[i][j - 1][k], dp[i - 1][j][3])
            if items[i][j] == 0:
                continue
            for k in range(3, 0, -1):
                dp[i][j][k] = max(dp[i][j][k], dp[i][j][k - 1] + items[i][j])
    return dp[R][C][-1]


R, C, K, *rcv = map(int, open(0).read().split())

items = np.zeros((R + 1, C + 1), dtype=np.int32)
for r, c, v in zip(*[iter(rcv)] * 3):
    items[r][c] = v

print(solve())

Submission status: Accepted

Solution code:
import bisect
import sys,io
import math
from collections import deque
from heapq import heappush, heappop

input = sys.stdin.buffer.readline

def sRaw():
    return input().rstrip("\r")


def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))

INF = 1 << 29

DIV = (10**9) + 7
#DIV = 998244353

def mod_inv_prime(a, mod=DIV):
    return pow(a, mod-2, mod)


def mod_inv(a, b):
    r = a
    w = b
    u = 1
    v = 0
    while w != 0:
        t = r//w
        r -= t*w
        r, w = w, r
        u -= t*v
        u, v = v, u
    return (u % b+b) % b


def CONV_TBL(max, mod=DIV):
    fac, finv, inv = [0]*max, [0]*max, [0]*max
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1
    for i in range(2, max):
        fac[i] = fac[i-1]*i % mod
        inv[i] = mod - inv[mod % i] * (mod//i) % mod
        finv[i] = finv[i-1]*inv[i] % mod

    class CONV:
        def __init__(self):
            self.fac = fac
            self.finv = finv
            pass

        def ncr(self, n, k):
            if(n < k):
                return 0
            if(n < 0 or k < 0):
                return 0
            return fac[n]*(finv[k]*finv[n-k] % DIV) % DIV

    return CONV()


def cumsum(As):
    s = 0
    for a in As:
        s += a
        yield s


sys.setrecursionlimit(200005)


def dijkstra(G,start=0):
    heap = []
    cost = [INF]*len(G)
    heappush(heap,(0,start))
    while len(heap)!=0:
        c,n = heappop(heap)
        if cost[n] !=INF:
            continue
        cost[n]=c
        for e in G[n]:
            ec,v = e
            if cost[v]!=INF:
                continue
            heappush(heap,(ec+c,v))
    return cost


def main():
    R,C,K = isRaw()
    mas = [[0 for _ in range(C)]for _ in range(R)]
    for k in range(K):
        r,c,v = isRaw()
        mas[r-1][c-1]=v
    dp = [[[0 for _ in range(C)] for _ in range(R)] for _ in range(3)]

    dp0 = dp[0]
    dp1 = dp[1]
    dp2 = dp[2]

    dp0[0][0]=mas[0][0]
    dp1[0][0]=mas[0][0]
    dp2[0][0]=mas[0][0]

    for r in range(R):
        for c in range(C):
            mrc = mas[r][c]
            
            dp0[r][c] = mrc
            dp1[r][c] = mrc
            dp2[r][c] = mrc

            if r>0:
                dp0[r][c] = max(dp0[r][c], dp2[r-1][c]+mrc)
                dp1[r][c] = max(dp1[r][c], dp2[r-1][c]+mrc)
                dp2[r][c] = max(dp2[r][c], dp2[r-1][c]+mrc)
            if c>0:
                dp0[r][c] = max(dp0[r][c], dp0[r][c-1], mrc)
                dp1[r][c] = max(dp1[r][c], dp1[r][c-1], dp0[r][c-1]+mrc)
                dp2[r][c] = max(dp2[r][c], dp2[r][c-1], dp1[r][c-1]+mrc)

    print(max([dp[ni][-1][-1] for ni in range(3)]))

main()

Submission status: Accepted

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

dp0 = [[0 for i in range(C)] for j in range(R)]
dp1 = [[0 for i in range(C)] for j in range(R)]
dp2 = [[0 for i in range(C)] for j in range(R)] 
dp3 = [[0 for i in range(C)] for j in range(R)]

if masu[0][0] != 0:
    dp1[0][0] = masu[0][0]
for i in range(1,C):
    dp0[0][i] = max(dp0[0][i],dp0[0][i-1])
    dp1[0][i] = max(dp1[0][i],dp1[0][i-1])
    dp2[0][i] = max(dp2[0][i],dp2[0][i-1])
    dp3[0][i] = max(dp3[0][i],dp3[0][i-1])
    if masu[0][i] != 0:
        dp3[0][i] = max(dp3[0][i],dp2[0][i]+masu[0][i])
        dp2[0][i] = max(dp2[0][i],dp1[0][i]+masu[0][i])
        dp1[0][i] = max(dp1[0][i],dp0[0][i]+masu[0][i])




for i in range(1,R):
    for j in range(C):
        dp0[i][j] = max(dp0[i][j],dp0[i-1][j],dp1[i-1][j],dp2[i-1][j],dp3[i-1][j])
        if j != 0:
            dp0[i][j] = max(dp0[i][j],dp0[i][j-1])
            dp1[i][j] = max(dp1[i][j],dp1[i][j-1])
            dp2[i][j] = max(dp2[i][j],dp2[i][j-1])
            dp3[i][j] = max(dp3[i][j],dp3[i][j-1])
        if masu[i][j] != 0:
            dp3[i][j] = max(dp3[i][j],dp2[i][j]+masu[i][j])
            dp2[i][j] = max(dp2[i][j],dp1[i][j]+masu[i][j])
            dp1[i][j] = max(dp1[i][j],dp0[i][j]+masu[i][j])
print(max(dp0[-1][-1],dp1[-1][-1],dp2[-1][-1],dp3[-1][-1]))

Submission status: Accepted

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

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    #各行では連続した区間
    #行ごとに見ないと話が進まん，降りるタイミぐは各列高々3000こ，来るタイミングも同様
    
    mod=10**9+7
    R,C,K=MI()
    S=[[0]*(C+1) for _ in range(R+1)]

    
    for i in range(K):
        r,c,v=MI()
        S[r][c]=v
        
        
    dp1=[[0]*(C+1)for _ in range(R+1)]
    dp2=[[0]*(C+1)for _ in range(R+1)]
    dp3=[[0]*(C+1)for _ in range(R+1)]
    # dp[i][j][k]はi行j列まで見てその行でk個以下
    
    for i in range(R+1):
        for j in range(C+1):
            #S(i,j)からの移動を考える
            
            #右へ移動，-,拾わない，拾う
            if j+1<=C:
                dp1[i][j+1]=max(dp1[i][j+1],dp1[i][j],S[i][j+1])
                dp2[i][j+1]=max(dp2[i][j+1],dp2[i][j],dp1[i][j]+S[i][j+1])
                dp3[i][j+1]=max(dp3[i][j+1],dp3[i][j],dp2[i][j]+S[i][j+1])
            
            #下へ
            if i+1<=R:
                temp=max(dp1[i][j],dp2[i][j],dp3[i][j])
                dp1[i+1][j]=temp+S[i+1][j]
                
    ans=max(dp1[-1][-1],dp2[-1][-1],dp3[-1][-1])
        
    # for i in range(R+1):
    #     print(dp[i])
        
    print(ans)
                
        
    

main()

Submission status: Accepted

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

for i in range(r+1):
    for j in range(c+1):
        for m in range(4):
            tmp  =dp[m][i][j]
            if i+1<=r:
                dp[0][i+1][j] = max(tmp,dp[0][i+1][j])
                dp[1][i+1][j] = max(dp[1][i+1][j],tmp + g[i+1][j])
            if j+1<=c:
                dp[m][i][j+1] = max(dp[m][i][j+1],tmp)
                if m<3:
                    dp[m+1][i][j+1] = max(dp[m+1][i][j+1],tmp + g[i][j+1]) 
ans = 0
for m in range(4):
    ans = max(ans,dp[m][-1][-1])
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
def main(R,C,K,RCV):
    V=np.zeros((R+1,C+1),dtype=np.int64)
    for i in range(K):
        V[RCV[i][0]][RCV[i][1]]=RCV[i][2]
    d=np.zeros((R+1,C+1,4),dtype=np.int64)
    for i in range(R):
        for j in range(C):
            m=max(d[i][j+1])
            d[i+1][j+1][0]=m
            for k in range(3):
                d[i+1][j+1][k+1]=max(d[i+1][j][k+1],m+V[i+1][j+1],d[i+1][j][k]+V[i+1][j+1])
    return max(d[-1][-1])
import sys
readline=sys.stdin.buffer.readline
read=sys.stdin.buffer.read
if sys.argv[-1]=='ONLINE_JUDGE':
    from numba import*
    from numba.pycc import CC
    cc=CC('my_module')
    def cc_export(f,s):
        cc.export(f.__name__,s)(f)
        return njit(f)
    main=cc_export(main,(i8,i8,i8,i8[:,:],))
    cc.compile()
    exit()
R,C,K=np.array(readline().split(),dtype=np.int64)
RCV=np.array(read().split(),dtype=np.int64).reshape(K,3)
from my_module import main
print(main(R,C,K,RCV))

Submission status: Accepted

Solution code:
import sys

R, C, K = map(int, input().split())
item = [[0] * (C + 1) for _ in range(R + 1)]  # dp配列と合わせるために, 0行目, 0列目を追加している.
for s in sys.stdin.readlines():
    r, c, v = map(int, s.split())
    item[r][c] = v

dp = [[[0] * (C + 1) for _ in range(R + 1)] for _ in range(4)]
for i in range(R + 1):
    for j in range(C + 1):
        for k in range(4):
            here = dp[k][i][j]
            if i + 1 <= R:
                dp[0][i + 1][j] = max(dp[0][i + 1][j], here)
                dp[1][i + 1][j] = max(dp[1][i + 1][j], here + item[i + 1][j])
            if j + 1 <= C:
                dp[k][i][j + 1] = max(dp[k][i][j + 1], here)
                if k < 3:
                    dp[k + 1][i][j + 1] = max(dp[k + 1][i][j + 1], here + item[i][j + 1])
ans = 0
for k in range(4):
    ans = max(ans, dp[k][-1][-1])
print(ans)

Submission status: Accepted

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

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

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

for h in range(R+1):
    for w in range(C+1):
        for k in range(4):
            position = dp[k][h][w]
            if h+1 <= R:
                # 移動先のアイテムを取らない場合
                dp[0][h+1][w] = max(dp[0][h+1][w], position)
                 # 移動先のアイテムを取る場合
                dp[1][h+1][w] = max(dp[1][h+1][w], position+item[h+1][w])
            if w+1 <= C:
                # 移動先のアイテムを取らない場合
                dp[k][h][w+1] = max(dp[k][h][w+1], position)
                # 現在のkが3未満のときのみ, 移動先のアイテムを取ることが可能
                if k < 3:
                    dp[k+1][h][w+1] = max(dp[k+1][h][w+1], position+item[h][w+1])

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

print(ans)

Submission status: Accepted

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

def main():
    R, C, K = map(int, readline().split())
    items = np.array(read().split(), dtype=np.int64)
    print(calc(R, C, K, items))

@njit(i8(i8, i8, i8, i8[:]), cache=True)
def calc(R, C, K, items):
    cell = np.zeros((R, C), dtype=np.int64)
    for i in range(0, K*3, 3):
        x, y, c = items[i:i+3]
        cell[x-1, y-1] = c
    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    dp[0, 1, 0] = dp[1, 0, 0] = 0
    for i in range(1, R + 1):
        for j in range(1, C + 1):
            for k in range(4):
                dp[i, j, k] = max(dp[i, j, k], dp[i, j-1, k])
                if k > 0:
                    dp[i, j, k] = max(dp[i, j, k], dp[i, j, k-1])
                    dp[i, j, k] = max(dp[i, j, k], dp[i, j-1, k-1] + cell[i-1, j-1])
                if k == 1:
                    dp[i, j, 1] = max(dp[i, j, 1], dp[i-1, j, 3] + cell[i-1, j-1])
    return dp[R, C, 3]

if __name__ == "__main__":
    read = sys.stdin.buffer.read
    readline = sys.stdin.buffer.readline

    if __file__=="test.py":
        f = open("./in_out/input.txt", "r", encoding="utf-8")
        read = f.read
        readline = f.readline

    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

def main():
    R, C, K = map(int, input().split())
    S = [[0]*(C+1) for _ in range(R+1)]
    for i in range(K):
        r, c, v = map(int, input().split())
        S[r][c] = v

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

    for i in range(1,R+1):
        for j in range(1,C+1):
            V = S[i][j]
            for k in range(4):
                dp[0][i][j] = max(dp[0][i][j], dp[k][i-1][j])# アイテムを取らないで下に進む
                dp[1][i][j] = max(dp[1][i][j], dp[k][i-1][j] + V)# アイテムを取って下に進む
                dp[k][i][j] = max(dp[k][i][j], dp[k][i][j-1])# アイテムを取らないで右に進む
                if k > 0:
                    dp[k][i][j] = max(dp[k][i][j], dp[k-1][i][j-1] + V)# アイテムを取って右に進む
    ans = 0
    for k in range(4):
        ans = max(ans, dp[k][R][C])
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def exit(*argv, **kwarg):
    print(*argv, **kwarg)
    sys.exit()


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def a_int(): return int(read())


def ints(): return list(map(int, read().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque


'''
dp[i][j]...(0,0)からスタートして(i,j)に到達する経路のなかでの最大の価値
dp[i][j]=max(dp[i][j-1],dp[i-1][j]) + v[i][j]


dp[i][j][k] ... (0,0)からスタートして(i,j)に到達する経路のなかでi行目ですでにk(以下)個選んでいるときの最大の価値

遷移は、i,jのvを拾うときと拾わないときのmax
dp[i][j][k] = max(dp[i][j-1][k-1]+V[i,j], dp[i][j-1][k]
                  ) #k個のままのほうが価値が高いかk-1から拾ったほうが価値が高いか

上からの遷移 # 拾うか拾わないかでこうかな
dp[i][j][0]=max(dp[i][j-1][0],max_k(dp[i-1][j]))
dp[i][j][1]=max(dp[i][j-1][0],max_k(dp[i-1][j][k])+V[i][j])
'''

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

# dp = [[[0] * 4 for _ in ra(C)] for _ in ra(R)]
dp0 = [[0] * C for _ in ra(R)]
dp1 = [[0] * C for _ in ra(R)]
dp2 = [[0] * C for _ in ra(R)]
dp3 = [[0] * C for _ in ra(R)]

# dp[0][0][0] = 0
dp1[0][0] = V[0][0]
dp2[0][0] = V[0][0]
dp3[0][0] = V[0][0]

for j in ra(1, C):
    dp1[0][j] = max(dp1[0][j - 1], dp0[0][j - 1] + V[0][j])
    dp2[0][j] = max(dp2[0][j - 1], dp1[0][j - 1] + V[0][j])
    dp3[0][j] = max(dp3[0][j - 1], dp2[0][j - 1] + V[0][j])

for i in ra(1, R):
    dp0[i][0] = dp1[i - 1][0]
    dp1[i][0] = dp0[i][0] + V[i][0]
    # dp2[i][0] = dp0[i][0] + V[i][0]
    # dp3[i][0] = dp0[i][0] + V[i][0]


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

        dp0[i][j] = max(dp0[i][j - 1],  # 左
                        ma)  # 上

        dp1[i][j] = max(dp0[i][j - 1] + V[i][j],  # 左から来て拾う
                        dp1[i][j - 1],  # 拾わないほうが大きい場合もある
                        ma + V[i][j])  # 上から来て拾う

        dp2[i][j] = max(dp1[i][j - 1] + V[i][j], dp2[i][j - 1])
        dp3[i][j] = max(dp2[i][j - 1] + V[i][j], dp3[i][j - 1])


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

# print(*values, sep='\n')
# print(*dp, sep='\n')

# dp2 = [[-1] * C for _ in ra(R)]
# for i in ra(R):
#     for j in ra(C):
#         dp2[i][j] = max(dp[i][j])
# print(*dp2, sep='\n')

Submission status: Accepted

Solution code:
import sys
import numpy as np
from numba import njit, void, i8
input = sys.stdin.buffer.readline

def main():
    R, C, K = map(int, input().split())
    cell = np.full((R+1, C+1), 0, dtype=np.int64)
    for i in range(K):
        x, y, c = map(int, input().split())
        cell[x-1, y-1] = c
    print(calc(cell, R, C))

@njit(i8(i8[:,:],i8,i8))
def calc(cell, R, C):
    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    dp[0, 1, 0] = dp[1, 0, 0] = 0
    for i in range(1, R + 1):
        for j in range(1, C + 1):
            for k in range(4):
                dp[i, j, k] = max(dp[i, j, k], dp[i, j-1, k])
                if k > 0:
                    dp[i, j, k] = max(dp[i, j, k], dp[i, j, k-1])
                    dp[i, j, k] = max(dp[i, j, k], dp[i, j-1, k-1] + cell[i-1, j-1])
                if k == 1:
                    dp[i, j, 1] = max(dp[i, j, 1], dp[i-1, j, 3] + cell[i-1, j-1])
    return dp[R, C, 3]

if __name__ == "__main__":
    main()