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 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):
                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])
                if k > 0:
                    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, k] = max(dp[i, j, 1], dp[i-1, j, 3] + cell[i-1, j-1])
    return dp[R, C, 3]

if __name__ == "__main__":
    main()

Submission status: Accepted

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

for i in range(1, R+1):
    for j in range(1, C+1):
        for k in range(4):
            dp[0][i+1][j] = max(dp[0][i+1][j], dp[k][i][j])
            dp[1][i+1][j] = max(dp[1][i+1][j], dp[k][i][j] + T[i+1][j])
            dp[k][i][j+1] = max(dp[k][i][j+1], dp[k][i][j])
            if k <= 2:
                dp[k+1][i][j+1] = max(dp[k+1][i][j+1], dp[k][i][j] + T[i][j+1])
ans = 0
for k in range(4):
    ans = max(ans, dp[k][R][C])
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
H, W, K = map(int, input().split())
mat = [[0]*W for i in range(H)]

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

dp0 = [[-1 for i in range(W)] for i in range(H)]
dp1 = [[-1 for i in range(W)] for i in range(H)]
dp2 = [[-1 for i in range(W)] for i in range(H)]
dp3 = [[-1 for i in range(W)] for i in range(H)]

dp0[0][0] = 0
if mat[0][0] != 0:
    dp1[0][0] = mat[0][0]

for i in range(H):
    for j in range(W):
        m = max(dp0[i][j], dp1[i][j], dp2[i][j], dp3[i][j])
        if i+1 < H:
            dp1[i+1][j] = max(dp1[i+1][j], m+mat[i+1][j])
            dp0[i+1][j] = max(dp0[i+1][j], m)
        if j+1 < W:
            dp0[i][j+1] = 0
            dp1[i][j+1] = max(dp1[i][j+1], dp1[i][j], dp0[i][j]+mat[i][j+1])
            dp2[i][j+1] = max(dp2[i][j+1], dp2[i][j], dp1[i][j]+mat[i][j+1])
            dp3[i][j+1] = max(dp3[i][j+1], dp3[i][j], dp2[i][j]+mat[i][j+1])

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

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

    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    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

    f(dp, cell, R, C)

    print(dp[R, C, 3])

@njit(void(i8[:,:,:],i8[:,:],i8,i8))
def f(dp, cell, R, C):
    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):
                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])
                if k > 0:
                    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, k] = max(dp[i, j, 1], dp[i-1, j, 3] + cell[i-1, j-1])

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys,collections as cl,bisect as bs,heapq as hq
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

def pow_k(x, n):
    ans = 1
    while n:
        if n % 2:
            ans *= x
        x *= x
        n >>= 1
    return ans

"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

r,c,k = m()


item = [[0 for j in range(c)] for i in range(r)]



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


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

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

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

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


ans = 0

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

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

    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    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

    f(dp, cell, R, C)

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

@njit(void(i8[:,:,:],i8[:,:],i8,i8))
def f(dp, cell, R, C):
    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):
                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])
                if k > 0:
                    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][k] = max(dp[i][j][1], dp[i-1][j][3] + cell[i-1][j-1])

if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    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

    f(dp, cell, R, C)

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

@njit(void(i8[:,:,:],i8[:,:],i8,i8))
def f(dp, cell, R, C):
    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):
                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])
                if k > 0:
                    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][k] = max(dp[i][j][1], dp[i-1][j][3] + cell[i-1][j-1])

if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

    L_INF = int(1e17)
    dp = np.full((R+1, C+1, 4), -L_INF, dtype=np.int64)
    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

    f(dp, cell, R, C)

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

@jit(void(i8[:,:,:],i8[:,:],i8,i8))
def f(dp, cell, R, C):
    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):
                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])
                if k > 0:
                    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][k] = max(dp[i][j][1], dp[i-1][j][3] + cell[i-1][j-1])

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
R, C, K, *RCV = [int(_) for _ in open(0).read().split()]
RCV = sorted([(r, -c, v) for r, c, v in zip(RCV[::3], RCV[1::3], RCV[2::3])])


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  # set value at position p (0-indexed)
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_right(self, p, v):  # apply operator from the right side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(dat[p], v)
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_left(self, p, v):  # apply operator from the left side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(v, dat[p])
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        vl = vr = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                vl = f(vl, dat[l])
                l += 1
            if r & 1:
                r -= 1
                vr = f(dat[r], vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


dp1 = SegmentTree([0] * (C + 1), max, -1)
dp2 = SegmentTree([0] * (C + 1), max, -1)
dp3 = SegmentTree([0] * (C + 1), max, -1)

rnow = 0
rcv = {}
for r, c, v in RCV:
    if rnow != r:
        rnow = r
        rcv[r] = []
    rcv[r] += [(-c, v)]
for r in sorted(rcv.keys()):
    cv = rcv[r]
    for c, v in cv:
        dp1.update(c, dp3.query(0, c + 1) + v)
    for c, v in cv:
        dp2.update(c, max(dp1.query(c, c + 1), dp1.query(0, c) + v))
    for c, v in cv:
        dp3.update(c, max(dp2.query(c, c + 1), dp2.query(0, c) + v))
ans = dp3.query(0, C + 1)
print(ans)

Submission status: Accepted

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

dp = [[[0] * (C+1) for _ in range(R+1)] for _ in range(4)] # dp[4][R+1][C+1]
index = 0
for i in range(1, R+1):
    for j in range(1, C+1):
        #移動
        for k in range(4):
            if dp[0][i][j] < dp[k][i-1][j]:
                dp[0][i][j] = dp[k][i-1][j]
            if dp[k][i][j] < dp[k][i][j-1]:
                dp[k][i][j] = dp[k][i][j-1]
        #あれば、拾うかどうか
        if i * 30000 + j in points_dict:
            v = points_dict[i * 30000 + j]
            for k in range(3, 0, -1):
                if dp[k][i][j] < dp[k-1][i][j] + v:
                    dp[k][i][j] = dp[k-1][i][j] + v
"""
for i in range(4):
    print(i)
    print(*dp[i], sep = '\n')
"""
print(max((dp[i][R][C] for i in range(4))))

Submission status: Accepted

Solution code:
r,c,k = map(int,input().split())
t = [[0 for i in range(c)] for i in range(r)]
for i in range(k):
    a,b,z = map(int,input().split())
    t[a-1][b-1] = z
dp = [[[0 for i in range(c)]for i in range(r)]for i in range(4)]
dp[0][0][0] = 0
dp[1][0][0] = t[0][0]
dp[2][0][0] = t[0][0]
dp[3][0][0] = t[0][0]
for i in range(r-1):
    dp[0][i+1][0] = dp[1][i][0]
    for j in range(1,4):
        dp[j][i+1][0] = dp[1][i][0]+t[i+1][0]
for i in range(c-1):
    dp[0][0][i+1] = 0
    for j in range(1,4):
        dp[j][0][i+1] = max(dp[1][0][i],t[0][i+1])
    for j in range(2,4):
        dp[j][0][i+1] = max(dp[2][0][i],dp[1][0][i]+t[0][i+1])
    dp[3][0][i+1] = max(dp[3][0][i],dp[2][0][i]+t[0][i+1])
for i in range(r-1):
    for j in range(c-1):
        u = max(dp[0][i+1][j],dp[3][i][j+1])
        for s in range(0,4):
            dp[s][i+1][j+1] =  u
        u = max(dp[0][i+1][j]+t[i+1][j+1],dp[1][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
        for s in range(1,4):
            dp[s][i+1][j+1] = u
        u = max(dp[1][i+1][j]+t[i+1][j+1],dp[2][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
        for s in range(2,4):
            dp[s][i+1][j+1] = u
        dp[3][i+1][j+1] = max(dp[2][i+1][j]+t[i+1][j+1],dp[3][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
print(dp[3][r-1][c-1])

Submission status: Accepted

Solution code:
def run():
    # sys.stdin.readline()
    import sys
    input = sys.stdin.readline
    r,c,k = map(int,input().split())
    t = [[0 for i in range(c)] for i in range(r)]
    for i in range(k):
        a,b,z = map(int,input().split())
        t[a-1][b-1] = z
    t = tuple(t)
    dp = [[[0 for i in range(c)]for i in range(r)]for i in range(4)]
    dp[0][0][0] = 0
    dp[1][0][0] = t[0][0]
    dp[2][0][0] = t[0][0]
    dp[3][0][0] = t[0][0]
    for i in range(r-1):
        dp[0][i+1][0] = dp[1][i][0]
        for j in range(1,4):
            dp[j][i+1][0] = dp[1][i][0]+t[i+1][0]
    for i in range(c-1):
        dp[0][0][i+1] = 0
        for j in range(1,4):
            dp[j][0][i+1] = max(dp[1][0][i],t[0][i+1])
        for j in range(2,4):
            dp[j][0][i+1] = max(dp[2][0][i],dp[1][0][i]+t[0][i+1])
        dp[3][0][i+1] = max(dp[3][0][i],dp[2][0][i]+t[0][i+1])
    for i in range(r-1):
        for j in range(c-1):
            u = max(dp[0][i+1][j],dp[3][i][j+1])
            for s in range(0,4):
                dp[s][i+1][j+1] =  u
            u = max(dp[0][i+1][j]+t[i+1][j+1],dp[1][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
            for s in range(1,4):
                dp[s][i+1][j+1] = u
            u = max(dp[1][i+1][j]+t[i+1][j+1],dp[2][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
            for s in range(2,4):
                dp[s][i+1][j+1] = u
            dp[3][i+1][j+1] = max(dp[2][i+1][j]+t[i+1][j+1],dp[3][i+1][j],dp[3][i][j+1]+t[i+1][j+1])
    print(dp[3][r-1][c-1])

if __name__ == "__main__":
    run()

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
H,W,K=map(int,input().split())
G=[[0]*W for i in range(H)]

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


dp0=[[-1 for i in range(W)] for i in range(H)]
dp1=[[-1 for i in range(W)] for i in range(H)]
dp2=[[-1 for i in range(W)] for i in range(H)]
dp3=[[-1 for i in range(W)] for i in range(H)]

dp0[0][0]=0
if G[0][0]!=0:
    dp1[0][0]=G[0][0]

for i in range(H):
    for j in range(W):
        m=max(dp0[i][j],dp1[i][j],dp2[i][j],dp3[i][j])
        if i+1<H:
            dp1[i+1][j]=max(dp1[i+1][j],m+G[i+1][j])
            dp0[i+1][j]=max(dp0[i+1][j],m)
        if j+1<W:
                dp0[i][j+1]=0
                dp1[i][j+1]=max(dp1[i][j+1],dp1[i][j],dp0[i][j]+G[i][j+1])
                dp2[i][j+1]=max(dp2[i][j+1],dp2[i][j],dp1[i][j]+G[i][j+1])
                dp3[i][j+1]=max(dp3[i][j+1],dp3[i][j],dp2[i][j]+G[i][j+1])
print(max(dp0[H-1][W-1],dp1[H-1][W-1],dp2[H-1][W-1],dp3[H-1][W-1]))

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def make_grid_int(h, w, num): return [[int(num)] * w for _ in range(h)]


def main():
    R, C, K = NMI()
    grid = make_grid_int(R, C, 0)
    for i in range(K):
        r, c, v = NMI()
        grid[r-1][c-1] = v

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

    for r in range(R+1):
        for c in range(C+1):
            now0 = dp0[r][c]
            now1 = dp1[r][c]
            now2 = dp2[r][c]
            now3 = dp3[r][c]
            try:
                val = grid[r][c]
            except:
                val = 0

            dp0[r+1][c] = max(now3, dp0[r+1][c])

            # 取って下
            dp0[r+1][c] = max(now0 + val, now1 + val, now2 + val, dp0[r+1][c])
            # 取らずに下
            dp0[r+1][c] = max(now0, now1, now2, now3, dp0[r+1][c])
            # 取って横
            dp1[r][c+1] = max(now0 + val, dp1[r][c+1])
            dp2[r][c+1] = max(now1 + val, dp2[r][c+1])
            dp3[r][c+1] = max(now2 + val, dp3[r][c+1])

            # 取らずに横
            dp1[r][c+1] = max(now1, dp1[r][c+1])
            dp2[r][c+1] = max(now2, dp2[r][c+1])
            dp0[r][c+1] = max(now0, dp0[r][c+1])

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


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

def main():
    r,c,k=MI()
    #dp=[[[-inf]*4 for j in range(c)]  for i in range(r)]
    dp0=[[-inf]*c for i in range(r)]
    dp1=[[-inf]*c for i in range(r)]
    dp2=[[-inf]*c for i in range(r)]
    dp3=[[-inf]*c for i in range(r)]
    val=[[0]*c for i in range(r)]
    for i in range(k):
        x,y,v=MI()
        val[x-1][y-1]=v
    if val[0][0]>0:
        dp1[0][0]=val[0][0]
        dp0[0][0]=0
    else:
        dp0[0][0]=0
    #print(dp)
    for i in range(r):
        for j in range(c):
            if i<r-1:
                if val[i+1][j]>0:
                        dp1[i+1][j]=max(dp1[i+1][j],dp0[i][j]+val[i+1][j],dp1[i][j]+val[i+1][j],dp2[i][j]+val[i+1][j],dp3[i][j]+val[i+1][j])
                dp0[i+1][j]=max(dp0[i+1][j],dp0[i][j],dp1[i][j],dp2[i][j],dp3[i][j])                 
            if j<c-1:
                if val[i][j+1]>0:
                    dp1[i][j+1]=max(dp1[i][j+1],dp0[i][j]+val[i][j+1])
                    dp2[i][j+1]=max(dp2[i][j+1],dp1[i][j]+val[i][j+1])
                    dp3[i][j+1]=max(dp3[i][j+1],dp2[i][j]+val[i][j+1])
                    #for k in range(1,4):
                        #dp[i][j+1][k]=max(dp[i][j+1][k],dp[i][j][k-1]+val[i][j+1])
                dp0[i][j+1]=max(dp0[i][j+1],dp0[i][j])
                dp1[i][j+1]=max(dp1[i][j+1],dp1[i][j])
                dp2[i][j+1]=max(dp2[i][j+1],dp2[i][j])
                dp3[i][j+1]=max(dp3[i][j+1],dp3[i][j])
                #for k in range(4):
                    #dp[i][j+1][k]=max(dp[i][j+1][k],dp[i][j][k])
    #print(dp0)
    #print(dp1)
    #print(dp2)
    #print(dp3)
    print(max(dp0[-1][-1],dp1[-1][-1],dp2[-1][-1],dp3[-1][-1]))
if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:

def resolve():
    R, C, K = map(int, input().split())
    G = [[0] * (C + 1) for _ in range(R + 1)]
    for _ in range(K):
        r, c, v = map(int, input().split())
        G[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 + G[i + 1][j])
                # 次の列に移動する場合
                if j + 1 <= C:
                    # 移動先のアイテムを取らない場合
                    dp[k][i][j + 1] = max(dp[k][i][j + 1], here)
                    # 現在のkが3未満のときのみ, 移動先のアイテムを取ることが可能
                    if k < 3:
                        dp[k + 1][i][j + 1] = max(dp[k + 1][i][j + 1], here + G[i][j + 1])
    ans = 0
    for k in range(4):
        ans = max(ans, dp[k][-1][-1])
    print(ans)


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
def main():
    r, c, k = map(int, input().split())
    d = [[0]*c for _ in [0]*r]
    for _ in range(k):
        t1, t2, t3 = map(int, input().split())
        d[t1-1][t2-1] = t3
    dp = [[0]*4 for _ in [0]*c]
    dp[0][1] = d[0][0]
    for x in range(r):
        dp2 = [[0]*4 for _ in [0]*c]
        for y in range(c):
            for z in range(4):
                if y != c-1:
                    if z != 3:
                        dp[y+1][z+1] = max(dp[y+1]
                                           [z+1], dp[y][z]+d[x][y+1])
                    dp[y+1][z] = max(dp[y+1][z], dp[y][z])
            if x != r-1:
                dp2[y][1] = max(dp2[y][1],
                                max(dp[y])+d[x+1][y])
                dp2[y][0] = max(dp2[y][0], max(dp[y]))
        if x != r-1:
            dp = dp2
    print(max(dp[c-1]))


main()

Submission status: Accepted

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal
from numba import jit

@jit
def run_dp(MAP, dp, R, C):
    for i in range(1, R+1):
        for j in range(1, C+1):
            for k in range(4):
                dp[i,j,0] = max(dp[i,j,0], dp[i-1,j,k])
                if MAP[i,j]:
                    dp[i,j,1] = max(dp[i,j,1], dp[i-1,j,k]+MAP[i,j])

                dp[i,j,k] = max(dp[i,j,k], dp[i,j-1,k])
                if MAP[i][j] and k < 3:
                    dp[i,j,k+1] = max(dp[i,j,k+1], dp[i,j-1,k] + MAP[i,j])
    return dp[R, C].max()

def run():
    R,C,K = map(int, sysread().split())
    MAP = np.zeros((R + 1, C + 1), dtype=np.int64)
    for i in range(K):
        r, c, v = map(int, sysread().split())
        MAP[r, c] = v

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

    run_dp(MAP, dp, R, C)

    #print(dp)
    #for m in MAP:
    #   print(m)
    ans= run_dp(MAP, dp, R, C)

    print(ans)

if __name__ == "__main__":
    run()