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: Wrong Answer

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.a, self.b, self.c = ls  # aが一番大きい

    def append(self, x):
        # xを突っ込む 3つのままに保つ
        # ついでに取れなくなったもののスコアを吐き出す
        if x < self.c:
            return x
        if x < self.b:
            ret = self.c
            self.c = x
            return ret
        if x < self.a:
            ret = self.c
            self.c = self.b
            self.b = x
            return ret
        if x >= self.a:
            ret = self.c
            self.c = self.b
            self.b = self.a
            self.a = x
            return ret


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

同じ行のアイテムは3つしか拾えないのはどうしようか...
各行でアイテムの価値をsortedlistに突っ込んでおくのは？ top3つ持ってればいいからそんなデータ構造いらない

dpだけじゃなくて行方向にいままでどんな要素を選んだか記録する必要あり
ritmとする。
横方向の移動があったときだけ中身を継承する(これはスコア算出に使う)
'''

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

dp = [[-1] * C for _ in ra(R)]
dp[0][0] = values[0][0]
for i in ra(1, R):
    dp[i][0] = values[i][0] + dp[i - 1][0]

top3 = Top3(ls=[values[0][0], 0, 0])
for j in ra(1, C):
    dp[0][j] = dp[0][j - 1] + values[0][j] - \
        top3.append(values[0][j])

for i in ra(1, R):
    top3 = Top3(ls=[values[i][0], 0, 0])  # 行のitemをもつ
    for j in ra(1, C):
        top = dp[i - 1][j] + values[i][j]
        left = dp[i][j - 1] + values[i][j] - \
            top3.append(values[i][j])  # top3を考慮した横のスコア
        # もしtopが大きければtop3は採用しない
        if top > left:
            dp[i][j] = top
            top3 = Top3(ls=[values[i][j], 0, 0])
        else:
            dp[i][j] = left
            # appendしたtop3を次も継続して使う
        # dp[i][j] = max(top, left)

print(dp[-1][-1])
# print(*dp, sep='\n')

Submission status: Wrong Answer

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.a, self.b, self.c = ls  # aが一番大きい

    def append(self, x):
        # xを突っ込む 3つのままに保つ
        # ついでに取れなくなったもののスコアを吐き出す
        if x < self.c:
            return x
        if x < self.b:
            ret = self.c
            self.c = x
            return ret
        if x < self.a:
            ret = self.c
            self.c = self.b
            self.b = x
            return ret
        if x >= self.a:
            ret = self.c
            self.c = self.b
            self.b = self.a
            self.a = x
            return ret


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

同じ行のアイテムは3つしか拾えないのはどうしようか...
各行でアイテムの価値をsortedlistに突っ込んでおくのは？ top3つ持ってればいいからそんなデータ構造いらない

dpだけじゃなくて行方向にいままでどんな要素を選んだか記録する必要あり
ritmとする。
横方向の移動があったときだけ中身を継承する(これはスコア算出に使う)
'''

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

dp = [[-1] * C for _ in ra(R)]
dp[0][0] = values[0][0]
for i in ra(1, R):
    dp[i][0] = values[i][0] + dp[i - 1][0]

top3 = Top3(ls=[values[0][0], 0, 0])
for j in ra(1, C):
    dp[0][j] = dp[0][j - 1] + values[0][j] - \
        top3.append(values[0][j])

for i in ra(1, R):
    top3 = Top3(ls=[values[i][0], 0, 0])  # 行のitemをもつ
    for j in ra(1, C):
        top = dp[i - 1][j] + values[i][j]
        left = dp[i][j - 1] + values[i][j] - \
            top3.append(values[i][j])  # top3を考慮した横のスコア
        # もしtopが大きければtop3は採用しない
        if top >= left:
            dp[i][j] = top
            top3 = Top3(ls=[values[i][j], 0, 0])
        else:
            dp[i][j] = left
            # appendしたtop3を次も継続して使う
        # dp[i][j] = max(top, left)

print(dp[-1][-1])
# print(*dp, sep='\n')

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline

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

# dp[R][C][taken 0 - 2]
dp = [[[-1] * 4 for _ in range(C + 1)] for _ in range(R + 1)]
dp[0][0][0] = 0
for j in range(C):
    for i in range(R):
        for k in range(3):
            if dp[i][j][k] == -1:
                continue
            # Use
            if field[i][j] and k < 3:
                dp[i][j+1][k+1] = max(dp[i][j+1][k+1], dp[i][j][k] + field[i][j]) 
                dp[i+1][j][0] = max(dp[i+1][j][0], dp[i][j][k] + field[i][j]) 
            # No use down
            dp[i+1][j][0] = max(dp[i+1][j][0], dp[i][j][k]) 
            # No use right
            dp[i][j+1][k] = max(dp[i][j+1][k], dp[i][j][k]) 

ans = 0
for i in range(4):
    for j in range(R + 1):
        ans = max(ans, dp[j][-1][i])
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as dd
R,C,K = map(int,input().split())
rcv = [tuple(map(int,input().split())) for _ in range(K)]
dp = [[[0]*5 for __ in range(C)] for _ in range(R)]
# dp[0][0][0] = 0

rc = dd(int)
for r,c,v in rcv:
    rc[(r-1,c-1)] = v

dp[0][0][1] = rc[(0,0)]
for r in range(R):
    for c in range(C):
        val = rc[(r,c)]
        if val != 0:
            for k in range(4):
                if c != 0:
                    dp[r][c][k+1] = max(dp[r][c-1][k] + val, dp[r][c][k+1])
                    dp[r][c][k] = max(dp[r][c-1][k], dp[r][c][k])
                if r != 0:
                    dp[r][c][0] = max(dp[r-1][c][k] + val, dp[r][c][0])
                    dp[r][c][0] = max(dp[r-1][c][0], dp[r][c][0])
        else:
            for k in range(4):
                if c != 0:
                    dp[r][c][k+1] = max(dp[r][c-1][k], dp[r][c][k+1])
                if r != 0:
                    dp[r][c][0] = max(dp[r-1][c][k], dp[r][c][0])

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

Submission status: Wrong Answer

Solution code:
R,C,K = map(int,input().split())
V = [[0]*C for i in range(R)]
dp = [[list() for i in range(C)] for i in range(R)]
for i in range(R):
    dp[i][0] = [(0,0)]
for j in range(C):
    dp[0][j] = [(0,0)]
for i in range(K):
    r,c,v = map(int,input().split())
    V[r-1][c-1] = v
for i in range(R):
    print(i)
    for j in range(C):
        if i > 0:
            if V[i][j] > 0:
                for count, score in dp[i-1][j]:
                    dp[i][j] += [(1, score + V[i][j])]
                    dp[i][j] += [(0, score)]
            else:
                for count, score in dp[i-1][j]:
                    dp[i][j] += [(0, score)]
        if j > 0:
            if V[i][j] > 0:
                for count, score in dp[i][j-1]:
                    if count == 3:
                        dp[i][j] += [(3, score)]
                    else:
                        dp[i][j] += [(count + 1, score + V[i][j])]
                        dp[i][j] += [(count, score)]
            else:
                for count, score in dp[i][j-1]:
                    dp[i][j] += [(count, score)]
ans = 0
for c, s in dp[R-1][C-1]:
    ans = max(ans, s)
print(ans)

Submission status: Wrong Answer

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.a, self.b, self.c = ls  # aが一番大きい

    def append(self, x):
        # xを突っ込む 3つのままに保つ
        # ついでに取れなくなったもののスコアを吐き出す
        if x < self.c:
            return x
        if x < self.b:
            ret = self.c
            self.c = x
            return ret
        if x < self.a:
            ret = self.c
            self.c = self.b
            self.b = x
            return ret
        if x >= self.a:
            ret = self.c
            self.c = self.b
            self.b = self.a
            self.a = x
            return ret


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

同じ行のアイテムは3つしか拾えないのはどうしようか...
各行でアイテムの価値をsortedlistに突っ込んでおくのは？ top3つ持ってればいいからそんなデータ構造いらない

dpだけじゃなくて行方向にいままでどんな要素を選んだか記録する必要あり
ritmとする。
横方向の移動があったときだけ中身を継承する(これはスコア算出に使う)
'''

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

dp = [[-1] * C for _ in ra(R)]
dp[0][0] = values[0][0]
for i in ra(1, R):
    dp[i][0] = values[i][0] + dp[i - 1][0]


# 素直なdpの実装
for i in ra(R):
    top3 = Top3(ls=[values[i][0], 0, 0])  # 行のitemをもつ
    for j in ra(1, C):
        if i - 1 >= 0:
            top = dp[i - 1][j] + values[i][j]
        else:
            top = -1
        left = dp[i][j - 1] + values[i][j] - \
            top3.append(values[i][j])  # top3を考慮した横のスコア
        # print(i, j)
        # print(dp[i][j - 1], values[i][j], left)

        # もしtopが大きければtop3は採用しない
        if top >= left:
            dp[i][j] = top
            top3 = Top3(ls=[values[i][j], 0, 0])
        else:
            dp[i][j] = left
            # appendしたtop3を次も継続して使う
        # dp[i][j] = max(top, left)

print(dp[-1][-1])
# print(*dp, sep='\n')

Submission status: Wrong Answer

Solution code:
R, C, K = map(int, input().split())
g = [[-float('inf')]*C for _ in range(R)]
for i in range(K):
    r, c, k = map(int, input().split())
    r -= 1
    c -= 1
    g[r][c] = k
g[R-1][C-1] = max(0, g[R-1][C-1])
dp = [[(0, 0, float('inf'))]*(C+1) for _ in range(R+1)]
for r in range(R):
    for c in range(C):
        if g[r][c] <= 0:
            continue
        w, s, m = dp[r][c]
        if (r+1) < R and g[r+1][c] >= 0:
            if dp[r+1][c][0] < w+g[r][c]:
                dp[r+1][c] = (w+g[r][c], 0, g[r+1][c])
        if (c+1) < C and g[r][c+1] >= 0:
            if dp[r][c+1][0] < w+g[r][c]:
                if s < 2:
                    dp[r][c+1] = (w+g[r][c], s+1, min(m, g[r][c+1]))
                else:
                    tw = w+g[r][c]-min(m, g[r][c])
                    if dp[r][c+1][0] < tw:
                        dp[r][c+1] = (tw, s+1, min(m, g[r][c]))

print(dp[R-1][C-1][0]+g[R-1][C-1])

Submission status: Wrong Answer

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

Items = [tuple(map(int, input().split())) for _ in range(K)]
Items.sort()

DP = [[[0,[],[]] for _ in range(C)] for __ in range(R)]
DP[0][0] = [0, [], []]
cnt = 0
y, x, v = Items[cnt]
y -= 1
x -= 1

if y == 0 and x == 0:
    DP[0][0] = [v,[v],[v]]
    cnt += 1
    if cnt >= K:
        y = -1
        x = -1
        v = -1
    else:
        y, x, v = Items[cnt]
    x -= 1
    y -= 1
for i in range(R):
    for j in range(C):
        if i == 0 and j == 0:
            continue
        if y == i and x == j:
            num1 = -float('inf')
            num2 = -float('inf')
            if i > 0:
                num1, X1, Y1 = DP[i-1][j]
                X1 = X1.copy()
                Y1 = Y1.copy()
                if len(X1) < 3:
                    num1 += v
                    X1.append(v)
                    Y1 = [v]
                else:
                    X1.sort(reverse=True)
                    Y1 = []
                    if X1[-1] < v:
                        num1 -= X1[-1]
                        X1[-1] = v
                        num1 += v
                        Y1 = [v]

            if j > 0:
                num2, X2, Y2 = DP[i][j-1]
                X2 = X2.copy()
                Y2 = Y2.copy()
                if len(Y2) < 3:
                    num2 += v
                    Y2.append(v)
                    X2 = [v]
                else:
                    Y2.sort(reverse=True)
                    if Y2[-1] < v:
                        num2 -= Y2[-1]
                        Y2[-1] = v
                        num2 += v
            if num1 >= num2:
                DP[i][j] = [num1, X1, Y1]
            else:
                DP[i][j] = [num2, X2, Y2]
            cnt += 1
            if cnt >= K:
                y, x, v = -1, -1, -1
            else:
                y, x, v = Items[cnt]
            y -= 1
            x -= 1

        else:
            if DP[i][j-1][0] >= DP[i-1][j][0]:
                DP[i][j] = DP[i][j-1]
            else:
                DP[i][j] = DP[i-1][j]
print(DP[R-1][C-1][0])

Submission status: Wrong Answer

Solution code:
R, C, K = map(int, input().split())
RCV = [[0]*C for i in range(R)]
for i in range(K):
    rcv = list(map(int, input().split()))
    r = rcv[0]-1
    c = rcv[1]-1
    v = rcv[2]
    RCV[r][c] = v
# for i in RCV:
#     print(i)

dp = [[0]*C for i in range(R)]
for i in range(R):
    base_num = 0
    sum_lst = [0, 0, 0]
    for j in range(C):
        if [i, j] == [0, 0]:
            sum_lst.append(RCV[i][j])
            sum_lst.sort()
            sum_lst = sum_lst[::-1]
            del sum_lst[-1]
            right = base_num + sum(sum_lst)
            dp[i][j] = right
        else:
            sum_lst.append(RCV[i][j])
            sum_lst.sort()
            sum_lst = sum_lst[::-1]
            del sum_lst[-1]
            down = dp[i-1][j] + RCV[i][j]
            right = base_num + sum(sum_lst)
            # print(i, j, down, right, sum_lst, base_num)
            if down < right:
                dp[i][j] = right
            else:
                dp[i][j] = down
                base_num = dp[i-1][j]
                sum_lst = [RCV[i][j], 0, 0]
# for i in dp:
#     print(i)
print(dp[-1][-1])

Submission status: Wrong Answer

Solution code:
r, c, k = map(int, input().split())
v = [map(int, input().split()) for _ in range(k)]

sq = [[0 for _ in range(c)] for _ in range(r)]
for ri, ci, vi in v:
    sq[ri - 1][ci - 1] = vi

dp = [[[0 for _ in range(c)] for _ in range(4)] for _ in range(2)]
for ri in range(r):
    if 0 < ri:
        for ci in range(c):
            dp[ri % 2][0][ci] = max([dp[1 - ri % 2][i][ci] for i in range(4)])
            for i in range(1, 4):
                dp[ri % 2][i][ci] = 0
    for ci in range(c):
        if 0 < ci:
            for i in range(4):
                dp[ri % 2][i][ci] = max(dp[ri % 2][i][ci], dp[ri % 2][i][ci - 1])
        if 0 < sq[ri][ci]:
            for i in range(2, -1, -1):
                dp[ri % 2][i + 1][ci] = max(dp[ri % 2][i + 1][ci], dp[ri % 2][i][ci] + sq[ri][ci])

ans = max([dp[-1][i][-1] for i in range(4)])
print(ans)

Submission status: Wrong Answer

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

for r in range(1, R+1):
    for c in range(1, C+1):
        A[r][c][1] = max(A[r-1][c][1], A[r][c-1][1])
        A[r][c][2] = max(A[r-1][c][2], A[r][c-1][2]) 
        A[r][c][3] = max(A[r-1][c][3], A[r][c-1][3])
        if B[r][c] != -1:
            A[r][c][1] = max(A[r][c][1], A[r][c-1][0]+B[r][c], A[r-1][c][1]+B[r][c])
            A[r][c][2] = max(A[r][c][2], A[r][c-1][1]+B[r][c], A[r-1][c][2]+B[r][c])
            A[r][c][3] = max(A[r][c][3], A[r][c-1][2]+B[r][c], A[r-1][c][3]+B[r][c])
print(max(A[R][C][0], A[R][C][1], A[R][C][2], A[R][C][3]))

Submission status: Wrong Answer

Solution code:
R, C, K = map(int, input().split())
g = [[-float('inf')]*C for _ in range(R)]
for i in range(K):
    r, c, k = map(int, input().split())
    r -= 1
    c -= 1
    g[r][c] = k
g[R-1][C-1] = max(0, g[R-1][C-1])
dp = [[(0, 0, float('inf'))]*(C+1) for _ in range(R+1)]
for r in range(R):
    for c in range(C):
        if g[r][c] <= 0:
            continue
        w, s, m = dp[r][c]
        if (r+1) < R and g[r+1][c] >= 0:
            if dp[r+1][c][0] < w+g[r][c]:
                dp[r+1][c] = (w+g[r][c], 0, g[r+1][c])
        if (c+1) < C and g[r][c+1] >= 0:
            if dp[r][c+1][0] < w+g[r][c]:
                if s < 2:
                    dp[r][c+1] = (w+g[r][c], s+1, min(m, g[r][c+1]))
                else:
                    tw = w+g[r][c]-min(m, g[r][c+1])
                    if dp[r][c+1][0] < tw:
                        dp[r][c+1] = (tw, s+1, min(m, g[r][c+1]))

print(dp[R-1][C-1][0]+g[R-1][C-1])

Submission status: Wrong Answer

Solution code:
R, C, K = map(int, input().split())
g = [[-float('inf')]*C for _ in range(R)]
for i in range(K):
    r, c, k = map(int, input().split())
    r -= 1
    c -= 1
    g[r][c] = k
g[R-1][C-1] = max(0, g[R-1][C-1])
dp = [[(0, 0, float('inf'))]*(C+1) for _ in range(R+1)]
for r in range(R):
    for c in range(C):
        if g[r][c] <= 0:
            continue
        w, s, m = dp[r][c]
        if (r+1) < R and g[r+1][c] >= 0:
            if dp[r+1][c][0] < w+g[r][c]:
                dp[r+1][c] = (w+g[r][c], 0, g[r+1][c])
        if (c+1) < C and g[r][c+1] >= 0:
            if dp[r][c+1][0] < w+g[r][c]:
                if s < 2:
                    dp[r][c+1] = (w+g[r][c], s+1, min(m, g[r][c+1]))
                else:
                    tw = w+g[r][c]-min(m, g[r][c+1])
                    if dp[r][c+1][0] < tw:
                        print(m, g[r][c+1])
                        dp[r][c+1] = (tw, s+1, min(m, g[r][c+1]))

print(dp[R-1][C-1][0]+g[R-1][C-1])

Submission status: Wrong Answer

Solution code:
R, C, K = map(int, input().split())
grid = [[0]*C for _ in range(R)]
for i in range(K):
    r, c, v= map(int, input().split())
    grid[r-1][c-1] = v
dp = [[[0]*4 for _ in range(C)] for _ in range(R)]
for i in range(R):
    for k in range(C):
        tmp = max(dp[i-1][k])
        target = grid[i][k]
        dp[i][k][0] = max(dp[i][k-1][0],tmp)
        dp[i][k][1] = dp[i][k-1][1]
        dp[i][k][2] = dp[i][k-1][2]
        dp[i][k][3] = dp[i][k-1][3]
        if target != 0:
            dp[i][k][1] = max(dp[i][k-1][0]+target,tmp+target,dp[i][k][1])
            dp[i][k][2] = max(dp[i][k-1][1]+target,dp[i][k][2])
            dp[i][k][3] = max(dp[i][k-1][2]+target,dp[i][k][3])
print(max(dp[-1][-1]))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

R,C,K = IL()
data = [[0 for i in range(C)] for j in range(R)]
for _ in range(K):
  j,i,v = IL()
  data[j-1][i-1] = v

dp = [[[0,0,0,0] for i in range(C+1)] for j in range(R+1)]
for j in range(R):
  for i in range(C):
    v = data[j][i] 
    if v == 0:
      dp[j+1][i+1][0] = max(dp[j+1][i][0],max(dp[j][i+1]))
      #dp[j+1][i+1][1] = max(dp[j+1][i][1],max(dp[j][i+1]))
      #dp[j+1][i+1][2] = max(dp[j+1][i][2],max(dp[j][i+1]))
      #dp[j+1][i+1][3] = max(dp[j+1][i][3],max(dp[j][i+1]))
    else:
      dp[j+1][i+1][0] = max(dp[j+1][i][0],max(dp[j][i+1]))
      #dp[j+1][i+1][1] = max(dp[j+1][i][1],dp[j+1][i][0]+v,max(dp[j][i+1])+v)
      #dp[j+1][i+1][2] = max(dp[j+1][i][2],dp[j+1][i][1]+v)
      #dp[j+1][i+1][3] = max(dp[j+1][i][3],dp[j+1][i][2]+v)
print(max(dp[-1][-1]))

Submission status: Wrong Answer

Solution code:
h,w,k=map(int,input().split())
dp=[[[0,[]]for _ in range(w+1)] for _ in range(h+1)]
for i in range(1,k+1):
  r,c,v=map(int,input().split())
  dp[r][c][0]=v
for i in range(h):
  for j in range(w):
    if dp[i+1][j][0]<=dp[i][j+1][0]:
      dp[i+1][j+1][1]=[dp[i+1][j+1][0]]
      dp[i+1][j+1][0]=dp[i][j+1][0]+dp[i+1][j+1][0]
    else:
      dp[i+1][j+1][1]=dp[i+1][j][1]+[dp[i+1][j+1][0]]
      if len(dp[i+1][j+1][1])<=3:
        dp[i+1][j+1][0]=dp[i+1][j][0]+dp[i+1][j+1][0]
      else:
        dp[i+1][j+1][0]=dp[i+1][j][0]+dp[i+1][j+1][0]-min(dp[i+1][j+1][1])
        dp[i+1][j+1][1].remove(min(dp[i+1][j+1][1]))
print(dp[h][w][0])

Submission status: Wrong Answer

Solution code:
from collections import deque
R, C, K = map(int, input().split())
S = [[0]*C for _ in range(R)]
d = [[0]*C for _ in range(R)]
for _ in range(K):
    r, c, v = map(int, input().split())
    S[r-1][c-1] = v
ans = [[0]*C for _ in range(R)]
h = 0
back = [0, 0, 0]
ans[0][0] = S[0][0]
que = deque([[0, 0, [S[0][0], 0, 0], 0]])

while que:
    h, w, backs, morau = que.popleft()
    for dh, dw in [1, 0], [0, 1]:
        nh, nw = h+dh, w+dw
        back = backs.copy()
        if 0<=nh<R and 0<=nw<C:
            if dh == 1:
                ans[nh][nw] = max(ans[nh][nw], morau+sum(back))
                que.append([nh, nw, [S[nh][nw], 0, 0], morau+sum(back)])
            if nh == R-1 and nw == C-1:
                ans[nh][nw] = max(ans[nh][nw], morau+sum(back)+S[nh][nw])
            if dw == 1:
                if S[nh][nw]:
                    min_ = min(back)
                    if min_ < S[nh][nw]:
                        for i in range(3):
                            if back[i] == min_:
                                back[i] = S[nh][nw]
                                break
                ans[nh][nw] = max(ans[nh][nw], sum(back)+morau, ans[h][w])
                que.append([nh, nw, back, morau])
print(ans[-1][-1])

Submission status: Wrong Answer

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

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

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

for i in range(R):
    for j in range(C):
        if i > 0:
            dp[i][j] = dp[i - 1][j]
            carry[i][j] = []
        if j > 0:
            if dp[i][j - 1] >= dp[i][j]:
                dp[i][j] = dp[i][j - 1]
                carry[i][j] = carry[i][j-1]

        dp[i][j] += items[i][j]
        carry[i][j].append(items[i][j])
        carry[i][j].sort()
        if len(carry[i][j]) >= 4:
            dp[i][j] -= carry[i][j][0]
            del carry[i][j][0]

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

Submission status: Wrong Answer

Solution code:
"""
各行ごとに、j列まで移動する場合のアイテム価値の最大値を求める。

0行目は、j列目まで進む
1行目は、j列目～k列目まで進む
2行目は、k列目

dp[i][j]　=> i行目j列目からスタートする場合の最大値
dp[i][j+1]で保持しているitem数が3つの場合、
dp[i][j]　= max(item[i][j]+dp[i+1][j]) or 
"""

from copy import copy
import heapq

R,C,K = map(int,input().split())
items = [[0]*(C) for _ in range(R)]

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

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

#R-1行目を初期化する
memo = [0,0,0]
heapq.heapify(memo)

heapq.heappush(memo,items[-1][-1])
dp[-1][-1] = items[-1][-1]
heapq.heappop(memo)

for j in range(C-2,-1,-1):
    v = items[-1][j]
    dp[-1][j] = dp[-1][j+1]
    heapq.heappush(memo,v)
    dp[-1][j] += v
    dp[-1][j] -= heapq.heappop(memo)

for i in range(R-2,-1,-1):
    memo = [0,0,0]
    heapq.heapify(memo)
    for j in range(C-1,-1,-1):
        v = items[i][j]
        if j != C-1:
            #右に進む場合の価値を求める。
            dp[i][j] = dp[i][j+1]
            heapq.heappush(memo,v)
            dp[i][j] += v
            dp[i][j] -= heapq.heappop(memo)
        
        #そのまま下に進む場合の価値を求める。
        tmp2 = dp[i+1][j] + v
        
        if tmp2 >= dp[i][j]:
            dp[i][j] = tmp2
            memo = [0,0,0]
            heapq.heapify(memo)
            heapq.heappush(memo,v)
            heapq.heappop(memo)

print(dp[0][0])

Submission status: Wrong Answer

Solution code:
"""
各行ごとに、j列まで移動する場合のアイテム価値の最大値を求める。

0行目は、j列目まで進む
1行目は、j列目～k列目まで進む
2行目は、k列目

dp[i][j]　=> i行目j列目からスタートする場合の最大値
dp[i][j+1]で保持しているitem数が3つの場合、
dp[i][j]　= max(item[i][j]+dp[i+1][j]) or 
"""

from copy import copy
import heapq

R,C,K = map(int,input().split())
items = [[0]*(C) for _ in range(R)]

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

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

#R-1行目を初期化する
memo = [0,0,0]
heapq.heapify(memo)

heapq.heappush(memo,items[-1][-1])
dp[-1][-1] = items[-1][-1]
heapq.heappop(memo)

for j in range(C-2,-1,-1):
    v = items[-1][j]
    dp[-1][j] = dp[-1][j+1]
    heapq.heappush(memo,v)
    dp[-1][j] += v
    dp[-1][j] -= heapq.heappop(memo)

for i in range(R-2,-1,-1):
    memo = [0,0,0]
    heapq.heapify(memo)
    for j in range(C-1,-1,-1):
        v = items[i][j]
        if j != C-1:
            #右に進む場合の価値を求める。
            dp[i][j] = dp[i][j+1]
            heapq.heappush(memo,v)
            dp[i][j] += v
            dp[i][j] -= heapq.heappop(memo)
        
        #そのまま下に進む場合の価値を求める。
        tmp2 = dp[i+1][j] + v
        
        if tmp2 > dp[i][j]:
            dp[i][j] = tmp2
            memo = [0,0,0]
            heapq.heapify(memo)
            heapq.heappush(memo,v)
            heapq.heappop(memo)

print(dp[0][0])