Problem:


Score : 500 points

Problem Statement

There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i.

Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square).

He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.

Find the maximum possible sum of the values of items he picks up.

Constraints

1 \leq R, C \leq 3000

1 \leq K \leq \min(2 \times 10^5, R \times C)

1 \leq r_i \leq R

1 \leq c_i \leq C

(r_i, c_i) \neq (r_j, c_j) (i \neq j)

1 \leq v_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R C K
r_1 c_1 v_1
r_2 c_2 v_2
:
r_K c_K v_K

Output

Print the maximum possible sum of the values of items Takahashi picks up.

Sample Input 1

2 2 3
1 1 3
2 1 4
1 2 5

Sample Output 1

8

He has two ways to get to the goal:

Visit (1, 1), (1, 2), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 5 = 8.

Visit (1, 1), (2, 1), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 4 = 7.

Thus, the maximum possible sum of the values of items he picks up is 8.

Sample Input 2

2 5 5
1 1 3
2 4 20
1 2 1
1 3 4
1 4 2

Sample Output 2

29

We have four items in the 1-st row. The optimal choices are as follows:

Visit (1, 1) (1, 2), (1, 3), (1, 4), (2, 4), and (2, 5), in this order, and pick up all items except the one on (1, 2). Then, the total value of the items he picks up will be 3 + 4 + 2 + 20 = 29.

Sample Input 3

4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10

Sample Output 3

142



Sample input:
2 2 3
1 1 3
2 1 4
1 2 5


Sample output:
8

Submission status: Time Limit Exceeded

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

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

for i in range(R):
  for j in range(C):
    dp[1][i][j] = max(dp[1][i][j],dp[0][i][j]+board[i][j])
    for k in range(4):
      if j>0:
        dp[k][i][j] = max(dp[k][i][j],dp[k][i][j-1])
      if j>0 and k>0:
        dp[k][i][j] = max(dp[k][i][j],dp[k-1][i][j-1]+board[i][j])
      if i>0:
        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]+board[i][j])
#print(*board,sep='\n')
#print(*dp,sep='\n')
print(max(max(dpij) for dpi in dp for dpij in dpi))

Submission status: Time Limit Exceeded

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


class Top3:
    def __init__(self, ls):
        self.ls = ls

    def append(self, x):
        # xを突っ込む 3つのままに保つ
        # ついでに取れなくなったもののスコアを吐き出す
        self.ls.append(x)
        mi = min(self.ls)
        self.ls.remove(mi)
        return mi

    @property
    def sum(self):
        return sum(self.ls)


'''
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 + 0)] for _ in ra(R + 0)]
# dp[0][0][0] = 0
for k in ra(1, 4):
    dp[0][0][k] = V[0][0]
for j in ra(1, C):
    for k in ra(1, 4):
        dp[0][j][k] = max(dp[0][j - 1][k], dp[0][j - 1][k - 1] + V[0][j])

for i in ra(1, R):
    dp[i][0][0] = max(dp[i - 1][0])
    dp[i][0][1] = dp[i][0][0] + V[i][0]
    dp[i][0][2] = dp[i][0][0] + V[i][0]
    dp[i][0][3] = dp[i][0][0] + V[i][0]


for i in ra(1, R):
    for j in ra(1, C):
        ma = max(dp[i - 1][j])
        dp[i][j][0] = max(dp[i][j - 1][0],  # 左
                          ma)  # 上

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

        dp[i][j][2] = max(dp[i][j - 1][1] + V[i][j], dp[i][j - 1][2])
        dp[i][j][3] = max(dp[i][j - 1][2] + V[i][j], dp[i][j - 1][3])


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

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

Submission status: Time Limit Exceeded

Solution code:
R, C, K = map(int, input().split())
M = [[0 for j in range(C+1)] for i in range(R+1)]
for i in range(K):
    r, c, v = map(int, input().split())
    M[r][c] = v
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):
        DP[i][j][0] = max(DP[i-1][j][0], DP[i-1][j][1], DP[i-1][j][2], DP[i-1][j][3], DP[i][j-1][0])
        DP[i][j][1] = max(DP[i-1][j][0]+M[i][j], DP[i-1][j][1]+M[i][j], DP[i-1][j][2]+M[i][j], DP[i-1][j][3]+M[i][j],
                          DP[i][j-1][0]+M[i][j],DP[i][j-1][1])
        DP[i][j][2] = max(DP[i][j-1][1] + M[i][j], DP[i][j-1][2])
        DP[i][j][3] = max(DP[i][j-1][2] + M[i][j], DP[i][j-1][3])
print(max(DP[R][C][0], DP[R][C][1], DP[R][C][2], DP[R][C][3]))

Submission status: Time Limit Exceeded

Solution code:
R, C, K = map(int, input().split())
M = [[0 for j in range(C+1)] for i in range(R+1)]
for i in range(K):
    r, c, v = map(int, input().split())
    M[r][c] = v
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):
        for k in range(4):
            if k == 0:
                DP[i][j][k] = max(DP[i-1][j][0], DP[i-1][j][1], DP[i-1][j][2], DP[i-1][j][3], DP[i][j-1][0])
            elif k == 1:
                DP[i][j][k] = max(DP[i-1][j][0]+M[i][j], DP[i-1][j][1]+M[i][j], DP[i-1][j][2]+M[i][j], DP[i-1][j][3]+M[i][j],
                                  DP[i][j-1][0]+M[i][j],DP[i][j-1][1])
            else:
                DP[i][j][k] = max(DP[i][j-1][k-1] + M[i][j], DP[i][j-1][k])
print(max(DP[R][C][0], DP[R][C][1], DP[R][C][2], DP[R][C][3]))

Submission status: Time Limit Exceeded

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

dp = [[[0 for k in range(4)] 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: Time Limit Exceeded

Solution code:
import sys
import numpy as np
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

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

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

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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


class Top3:
    def __init__(self, ls):
        self.ls = ls

    def append(self, x):
        # xを突っ込む 3つのままに保つ
        # ついでに取れなくなったもののスコアを吐き出す
        self.ls.append(x)
        mi = min(self.ls)
        self.ls.remove(mi)
        return mi

    @property
    def sum(self):
        return sum(self.ls)


'''
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 + 0)] for _ in ra(R + 0)]
# dp[0][0][0] = 0
for k in ra(1, 4):
    dp[0][0][k] = V[0][0]
for j in ra(1, C):
    for k in ra(1, 4):
        dp[0][j][k] = max(dp[0][j - 1][k], dp[0][j - 1][k - 1] + V[0][j])

for i in ra(1, R):
    dp[i][0][0] = max(dp[i - 1][0])
    dp[i][0][1] = dp[i][0][0] + V[i][0]
    dp[i][0][2] = dp[i][0][0] + V[i][0]
    dp[i][0][3] = dp[i][0][0] + V[i][0]


for i in ra(1, R):
    for j in ra(1, C):
        dp[i][j][0] = max(dp[i][j - 1][0],  # 左
                          max(dp[i - 1][j]))  # 上

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

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

        dp[i][j][2] = max(dp[i][j - 1][1] + V[i][j], dp[i][j - 1][2])
        dp[i][j][3] = max(dp[i][j - 1][2] + V[i][j], dp[i][j - 1][3])


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

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

Submission status: Time Limit Exceeded

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

dp = [[[0 for k in range(4)] 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):
    dp = [[0 for k in range(4)] for j in range(c)]
    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]


ans = 0

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

Submission status: Time Limit Exceeded

Solution code:
rows, cols, k = [int(z) for z in input().strip().split()]
value = [[0 for c in range(cols)] for r in range(rows)]
dp = [[[0, 0, 0, 0] for c in range(cols)] for r in range(rows)]
for i in range(k):
    r, c, v = [int(z) for z in input().strip().split()]
    value[r - 1][c - 1] = v
 
if value[0][0] > 0:
    dp[0][0][1] = value[0][0]
 
for r in range(1, rows):
    dp[r][0][0] = max(dp[r - 1][0][0], dp[r - 1][0][1], dp[r - 1][0][2], dp[r - 1][0][3])
    if value[r][0] > 0:
        dp[r][0][1] = dp[r][0][0] + value[r][0]
 
for c in range(1, cols):
    dp[0][c][0] = dp[0][c - 1][0]
    if value[0][c] > 0:
        dp[0][c][1] = max(dp[0][c - 1][1], dp[0][c - 1][0] + value[0][c])
        dp[0][c][2] = max(dp[0][c - 1][2], dp[0][c - 1][1] + value[0][c])
        dp[0][c][3] = max(dp[0][c - 1][3], dp[0][c - 1][2] + value[0][c])
    else:
        dp[0][c][1] = dp[0][c - 1][1]
        dp[0][c][2] = dp[0][c - 1][2]
        dp[0][c][3] = dp[0][c - 1][3]
 
for r in range(1, rows):
    for c in range(1, cols):
        up = max(dp[r - 1][c][0], dp[r - 1][c][1], dp[r - 1][c][2], dp[r - 1][c][3])
        dp[r][c][0] = max(dp[r][c - 1][0], up)
        if value[r][c] > 0:
            dp[r][c][1] = max(dp[r][c - 1][1], dp[r][c - 1][0] + value[r][c], up + value[r][c])
            dp[r][c][2] = max(dp[r][c - 1][2], dp[r][c - 1][1] + value[r][c])
            dp[r][c][3] = max(dp[r][c - 1][3], dp[r][c - 1][2] + value[r][c])
        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(int(max(dp[rows - 1][cols - 1])))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
R, C, K = map(int, input().split())

L_INF = int(1e17)
dp = [[[-L_INF] * 4 for _ in range(C+1)] for _ in range(R+1)]
cell = [[0] * (C+1) for _ in range(R+1)]

for i in range(K):
    x, y, c = map(int, input().split())
    cell[x-1][y-1] = 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])

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

Submission status: Time Limit Exceeded

Solution code:
import heapq

r, c, k = map(int, input().split())
k_mat = [[0 for _ in range(c)] for _ in range(r)]
for _ in range(k):
    x, y, v = map(int, input().split())
    x -= 1
    y -= 1
    k_mat[x][y] = v
dp = [[[0 for _ in range(4)] for _ in range(c+1)] for _ in range(r+1)]

# 初期化
for i in range(r):
    for j in range(c):
        for k in range(3)[::-1]:
            dp[i][j][k+1] = max(dp[i][j][k+1], dp[i][j][k] + k_mat[i][j])
        for k in range(4):
            dp[i+1][j][0] = max(dp[i+1][j][0], dp[i][j][k])
            dp[i][j+1][k] = max(dp[i][j+1][k], dp[i][j][k])

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import queue
import copy

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(tin())
mod=1000000007

#+++++

def rc_to_s(r,c):
	return str(r)+'_'+str(c)
	
def s_to_rc(s):
	r,c = map(int, s.split('_'))
	return r, c
	
class qqq:
	def __init__(self, n, base):
		self.l=[]
		self.sum=0
		self.num=0
		self.n_max=n
		self.base=base
	
	def update(self, v):
		if self.n_max==0:
			return 
			
		elif self.num==self.n_max and v > self.l[0]:
			self.l[0]=v
			self.l.sort()
			self.sum=sum(self.l)
			
		elif self.num < self.n_max:
			self.l.append(v)
			self.l.sort()
			self.sum += v
			self.num += 1
	
	def get_value(self):
		return self.sum+self.base
		
	def copy(self):
		ret=qqq(self.n_max, self.base)
		ret.l=self.l[:]
		ret.sum=self.sum
		ret.num=self.num
		return ret
			
			
def main():
	#a = int(input())
	r, c, k = tin()
	#s = input()
	dd={}
	for _ in range(k):
		ri, ci, vi = tin()
		dd[rc_to_s(ri-1,ci-1)]=vi
	
	cv=[0]*c
	pq=qqq(3, 0)
	for ci in range(c):
		ps = rc_to_s(0, ci)
		if ps in dd:
			pq.update(dd[ps])
		cv[ci]=pq.get_value()
	
	for ri in range(1, r):
		ncv = [0 for _ in range(c)]
		sts=[qqq(0,0),qqq(1,0),qqq(2,0),qqq(3,0)]
		
		for ci in range(c):
			sts[0] = qqq(0,cv[ci])
			
			ps = rc_to_s(ri, ci)
			if ps in dd:
				tv = dd[ps]
				for iii in [3,2,1]:
					sts[iii].update(tv)
					if sts[iii].get_value() < sts[iii-1].get_value() + tv:
						sts[iii]=sts[iii-1].copy()
						sts[iii].n_max=iii
						sts[iii].update(tv)
				
			ncv[ci]= max([v.get_value() for v in sts])
		cv=ncv
		pa(cv)
	return cv[-1]
		
	
	
	

		
	
	
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Time Limit Exceeded

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):
            for s in range(0,4):
                dp[s][i+1][j+1] =  max(dp[0][i+1][j],dp[3][i][j+1])
            for s in range(1,4):
                dp[s][i+1][j+1] = 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(2,4):
                dp[s][i+1][j+1] = 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])
            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: Time Limit Exceeded

Solution code:
H,W,K=map(int,input().split())

L=[[[0,0,0,0]for i in range(W+1)]for j in range(H+1)]

G={}

import sys
input=sys.stdin.readline
for i in range(K):
    h,w,g=map(int,input().split())
    G[(h,w)]=g
#print(G)

for h in range(1,H+1):
    for w in range(1,W+1):
        if (h,w) not in G:
            L[h][w][0]=max(L[h][w-1][0],max(L[h-1][w]))
            L[h][w][1]=L[h][w-1][1]
            L[h][w][2]=L[h][w-1][2]
            L[h][w][3]=L[h][w-1][3]
        else:
            L[h][w][0]=max(L[h][w-1][0],max(L[h-1][w]))
            L[h][w][1]=max(L[h][w-1][0]+G[(h,w)],max(L[h-1][w])+G[(h,w)],L[h][w-1][1])
            L[h][w][2]=max(L[h][w-1][2],L[h][w-1][1]+G[(h,w)])
            L[h][w][3]=max(L[h][w-1][3],L[h][w-1][2]+G[(h,w)])
#print(L)
print(max(L[H][W]))

Submission status: Time Limit Exceeded

Solution code:
R,C,K=map(int,input().split())
RCV=[list(map(int,input().split())) for i in range(K)]
V=[[0]*(C+1) for i in range(R+1)]
for r,c,v in RCV:
    V[r][c]=v
d=[[[0]*4 for i in range(C+1)] for i in range(R+1)]
for i in range(R):
    for j in range(C):
        m=max(d[i][j+1])
        d[i+1][j+1][0]=m
        d[i+1][j+1][1]=max(d[i+1][j][1],m+V[i+1][j+1],d[i+1][j][0]+V[i+1][j+1])
        d[i+1][j+1][2]=max(d[i+1][j][2],m+V[i+1][j+1],d[i+1][j][1]+V[i+1][j+1])
        d[i+1][j+1][3]=max(d[i+1][j][3],m+V[i+1][j+1],d[i+1][j][2]+V[i+1][j+1])
print(max(d[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
H,W,K=map(int,input().split())

L=[[[0,0,0,0]for i in range(W+1)]for j in range(H+1)]

G=[[0 for i in range(W+1)]for j in range(H+1)]

import sys
input=sys.stdin.readline
for i in range(K):
    h,w,g=map(int,input().split())
    G[h][w]+=g
#print(G)

for h in range(1,H+1):
    for w in range(1,W+1):
        L[h][w][0]=max(L[h][w-1][0],max(L[h-1][w]))
        L[h][w][1]=max(L[h][w-1][0]+G[h][w],max(L[h-1][w])+G[h][w],L[h][w-1][1])
        L[h][w][2]=max(L[h][w-1][2],L[h][w-1][1]+G[h][w])
        L[h][w][3]=max(L[h][w-1][3],L[h][w-1][2]+G[h][w])
#print(L)
print(max(L[H][W]))

Submission status: Time Limit Exceeded

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

dp=[[[-1,-1,-1,-1] for i in range(W)] for i in range(H)]

dp[0][0][0]=0
if G[0][0]!=0:
    dp[0][0][1]=G[0][0]

for i in range(H):
    for j in range(W):
        m=max(dp[i][j])
        if i+1<H:
            dp[i+1][j][1]=max(dp[i+1][j][1],m+G[i+1][j])
            dp[i+1][j][0]=max(dp[i+1][j][0],m)
        if j+1<W:
                dp[i][j+1][0]=0
                dp[i][j+1][1]=max(dp[i][j+1][1],dp[i][j][1],dp[i][j][0]+G[i][j+1])
                dp[i][j+1][2]=max(dp[i][j+1][2],dp[i][j][2],dp[i][j][1]+G[i][j+1])
                dp[i][j+1][3]=max(dp[i][j+1][3],dp[i][j][3],dp[i][j][2]+G[i][j+1])
print(max(dp[H-1][W-1]))

Submission status: Time Limit Exceeded

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
    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):
            for s in range(0,4):
                dp[s][i+1][j+1] =  max(dp[0][i+1][j],dp[3][i][j+1])
            for s in range(1,4):
                dp[s][i+1][j+1] = 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(2,4):
                dp[s][i+1][j+1] = 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])
            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: Time Limit Exceeded

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):
            for i in range(4):
                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()