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


def read_matrix(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


from heapq import heapify, heappop, heappush, heappushpop


class PriorityQueue:
    def __init__(self, heap):
        '''
        heap ... list
        '''
        self.heap = heap
        heapify(self.heap)

    def push(self, item):
        heappush(self.heap, item)

    def pop(self):
        return heappop(self.heap)

    def pushpop(self, item):
        return heappushpop(self.heap, item)

    def __call__(self):
        return self.heap

    def __len__(self):
        return len(self.heap)


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter, xor, add
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right
from functools import reduce


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

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


'''
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)
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 = 0
        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
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

r,c,k = map(int,readline().split())
data = list(map(int,read().split()))
d = dict()
it = iter(data)
for ri,ci,vi in zip(it,it,it):
    d[(ri-1)*5000 + (ci-1)] = vi

dp_max = [0] * (c)

for i in range(r):
    dp = [[0,0,0,0] for _ in range(4)]
    for j in range(c):
        dp[0][0] = max(dp[0][0],dp_max[j])
        if( i*5000+j  in d):
            ci = d[i*5000+j]
            #3
            min_num = min(dp[3][1:4])
            if(min_num < ci):
                dp[3][0] += ci-min_num
                for k in range(1,4):
                    if(dp[3][k] == min_num):
                        dp[3][k] = ci
                        break
            if(dp[3][0] <= dp[2][0] + ci):
                dp[3][0] = dp[2][0] + ci
                dp[3][1] = dp[2][1]
                dp[3][2] = dp[2][2]
                dp[3][3] = ci

            #2
            if(dp[2][0] <= dp[1][0] + ci):
                dp[2][0] = dp[1][0] + ci
                dp[3][1] = dp[1][1]
                dp[2][2] = ci
            #1
            if(dp[1][0] <= dp[0][0] + ci):
                dp[1][0] = dp[0][0] + ci
                dp[1][1] = ci

        dp_max[j] = max(dp[0][0], dp[1][0],dp[2][0],dp[3][0])

    # print(i,j)
    # print(dp_max)

print(dp_max[-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,[0,0,0]] for _ in range(C)]for _ in range(R)]

#R-1行目を初期化する
heapq.heappush(dp[-1][-1][1],items[-1][-1])
heapq.heappop(dp[-1][-1][1])
dp[-1][-1][0] = sum(dp[-1][-1][1])
for j in range(C-2,-1,-1):
    dp[-1][j][1] = copy(dp[-1][j+1][1])
    heapq.heappush(dp[-1][j][1],items[-1][j])
    heapq.heappop(dp[-1][j][1])
    dp[-1][j][0] = sum(dp[-1][j][1])

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

print(dp[0][0][0])

Submission status: Wrong Answer

Solution code:
R, C, K = map(int, input().split(" "))
board = [ [0]*(C+1) for _ in range(R+1) ]
for _ in range(K) :
    i, j, v = map(int, input().split(" "))
    board[i][j] = v

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

for i in range(1, R+1) :
    for j in range(1, C+1) : 
        if board[i][j] == 0 :
            for k in range(4) :
                score[i][j][k] = score[i][j-1][k]    
        else :
            for k in range(3):
                score[i][j][k+1] = score[i][j-1][k] + board[i][j]
        
        score[i][j][1] = max(max(score[i-1][j]) + board[i]
                             [j], score[i][j-1][1], score[i][j-1][0]+board[i][j])
        score[i][j][0] = max(score[i-1][j])



print(max(score[-1][-1]))

Submission status: Wrong Answer

Solution code:
R, C, K = map(int, input().split(" "))
board = [ [0]*(C+1) for _ in range(R+1) ]
for _ in range(K) :
    i, j, v = map(int, input().split(" "))
    board[i][j] = v

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

for i in range(1, R+1) :
    for j in range(1, C+1) : 
        if board[i][j] == 0 :
            for k in range(4) :
                score[i][j][k] = score[i][j-1][k]    
        else :
            for k in range(3):
                score[i][j][k+1] = score[i][j-1][k] + board[i][j]
        
        score[i][j][1] = max(max(score[i-1][j]) + board[i][j], score[i][j-1][1] )
        score[i][j][0] = max(score[i-1][j])



print(max(score[-1][-1]))

Submission status: Wrong Answer

Solution code:
f=lambda:map(int,input().split())
R,C,K=f()
g=[[0]*R for _ in range(C)]
for _ in range(K):
  r,c,v=f()
  g[c-1][r-1]=v
# print(g)
from heapq import *
dpo=[(0,0,[])]*(R+1)
for c in range(C):
  dpn=[(0,0,[])]
  for r in range(R):
    cp,cc,cq=dpo[r+1]
    rp,rc,rq=dpn[r]
    t=g[c][r]
    if t<1:
      if cp>rp: dpn+=[(cp,cc,cq)]
      else: dpn+=[(rp,0,[])]
      continue
    if cc>2:
      heappush(cq,t)
      dpn+=[(cp-heappop(cq)+t,1,cq)]
    elif cp>rp:
      heappush(cq,t)
      dpn+=[(cp+t,cc+1,cq)]
    else: dpn+=[(rp+t,1,[t])]
  dpo=dpn
  # print(dpn)
print(dpn[R][0])

Submission status: Wrong Answer

Solution code:
import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 19 + 7
EPS = 10 ** -10

H, W, K = MAP()
grid = list2d(H+1, W+1, 0)
for i in range(K):
    h, w, v = MAP()
    grid[h][w] = v

dp0 = list2d(H+1, W+1, -INF)
dp1 = list2d(H+1, W+1, -INF)
dp2 = list2d(H+1, W+1, -INF)
dp3 = list2d(H+1, W+1, -INF)
dp0[0][1] = dp0[1][0] = 0
for h in range(1, H+1):
    for w in range(1, W+1):
        dp0[h][w] = max(dp0[h-1][w], dp0[h-1][w], dp1[h-1][w],  dp2[h-1][w], dp3[h-1][w])
        dp1[h][w] = dp1[h][w-1]
        dp2[h][w] = dp2[h][w-1]
        dp3[h][w] = dp3[h][w-1]
        if grid[h][w]:
            dp1[h][w] = max(dp1[h][w], max(dp0[h][w-1], dp0[h-1][w], dp1[h-1][w], dp2[h-1][w], dp3[h-1][w]) + grid[h][w])
            dp2[h][w] = max(dp2[h][w], dp1[h][w-1] + grid[h][w])
            dp3[h][w] = max(dp3[h][w], dp2[h][w-1] + grid[h][w])
ans = max(dp0[H][W], dp1[H][W], dp2[H][W], dp3[H][W])
print(ans)

Submission status: Wrong Answer

Solution code:
import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 19 + 7
EPS = 10 ** -10

H, W, K = MAP()
grid = list2d(H+1, W+1, 0)
for i in range(K):
    h, w, v = MAP()
    grid[h][w] = v

dp0 = list2d(H+1, W+1, -INF)
dp1 = list2d(H+1, W+1, -INF)
dp2 = list2d(H+1, W+1, -INF)
dp3 = list2d(H+1, W+1, -INF)
dp0[0][1] = dp0[1][0] = 0
for h in range(1, H+1):
    for w in range(1, W+1):
        dp0[h][w] = max(dp0[h-1][w], dp0[h][w-1], dp1[h][w-1],  dp2[h][w-1], dp3[h][w-1])
        dp1[h][w] = dp1[h][w-1]
        dp2[h][w] = dp2[h][w-1]
        dp3[h][w] = dp3[h][w-1]
        if grid[h][w]:
            dp1[h][w] = max(dp1[h][w], max(dp0[h][w-1], dp0[h-1][w], dp1[h-1][w], dp2[h-1][w], dp3[h-1][w]) + grid[h][w])
            dp2[h][w] = max(dp2[h][w], dp1[h][w-1] + grid[h][w])
            dp3[h][w] = max(dp3[h][w], dp2[h][w-1] + grid[h][w])
ans = max(dp0[H][W], dp1[H][W], dp2[H][W], dp3[H][W])
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

def solve():
    input = sys.stdin.readline
    R, C, K = map(int, input().split())
    item = [[0 for _ in range(C)] for r in range(R)]
    for _ in range(K):
        r, c, k = map(int, input().split())
        item[r-1][c-1] = k
    
    DP = [[[-1 for _ in range(C)] for r in range(R)] for i in range(4)]
    visited = [[False for c in range(C)] for r in range(R)]
    q = deque()
    if C >= 2: DP[0][0][1] = 0
    visited[0][0] = True
    if item[0][0] > 0:
        if C >= 2: DP[1][0][1] = item[0][0]
        if R >= 2: DP[0][1][0] = item[0][0]
    
    if C >= 2: q.append((0, 1))
    if R >= 2: q.append((1, 0))
    while q:
        r, c = q.popleft()
        if not visited[r][c]:
            visited[r][c] = True
            for i in range(4):
                if DP[i][r][c] > -1:
                    if r + 1 < R: 
                        DP[0][r+1][c] = max(DP[0][r+1][c], DP[i][r][c])
                        q.append((r+1, c))
                    if c + 1 < C: 
                        DP[i][r][c+1] = max(DP[i][r][c+1], DP[i][r][c])
                        q.append((r, c+1))
                    if i < 3 and item[r][c] > 0:
                        if r + 1 < R: DP[0][r+1][c] = max(DP[0][r+1][c], DP[i][r][c] + item[r][c])
                        if c + 1 < C: DP[i+1][r][c+1] = max(DP[i+1][r][c+1], DP[i][r][c] + item[r][c])

    ans = DP[3][R-1][C-1]
    for i in range(3): ans = max(ans, DP[i][R-1][C-1] + item[R-1][C-1])
    print(ans)
    return 0

if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
import heapq
r,c,k = map(int,input().split())
#rcv = [[int(i) for i in input().split()] for j in range(k)]

dp = [[0 for i in range(c+1)] for j in range(r+1)]

val = [[0 for i in range(c+1)] for j in range(r+1)]

for i in range(k):
    r1,c1,v1 = map(int,input().split())
    val[r1][c1] = v1
    
#print(val)
    
for i in range(1,r+1):
    li = []
    heapq.heapify(li)
    num = 0
    for j in range(1,c+1):
        #print(val[i][j])
        if val[i][j] > 0:
            if num == 3:
                tmp = heapq.heappop(li)
                if tmp < val[i][j]:
                    heapq.heappush(li,val[i][j])
                    dp[i][j] = max(dp[i-1][j]+val[i][j],dp[i][j-1]+val[i][j]-tmp)
                else:
                    heapq.heappush(li,tmp)
                    dp[i][j] = max(dp[i-1][j],dp[i][j-1])
            else:
                num += 1
                heapq.heappush(li,val[i][j])
                dp[i][j] = max(dp[i-1][j]+val[i][j],dp[i][j-1]+val[i][j])
        else:
            dp[i][j] = max(dp[i-1][j],dp[i][j-1])
        
print(dp[r][c])

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


def read_matrix(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter, xor, add
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right
from functools import reduce


class Top3:
    def __init__(self, ls=[0, 0, 0]):
        self.ls = sorted(ls, reverse=True)[:3]

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

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

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

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

R, C, K = ints()
RCV = read_tuple(K)
values = defaultdict(lambda: 0)
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(R):
    dp[i][0] = values[i, 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 = 0
        # print(top3.ls)
        left = dp[i][j - 1] + values[i, j] - \
            top3.append(values[i, j])  # top3を考慮した横のスコア
        # left = dp[i][j - 1] + values[i, j]

        # もし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:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


r, c, l = LI()
grid = [[0] * c for _ in range(r)]

for a in range(l):
    ri, ci, vi = LI()
    grid[ri-1][ci-1] = vi

dp = [[[0] * 4 for _ in range(c)] for _ in range(r)]
for i in range(r):
    for j in range(c):
        if i:
            dp[i][j][0] = max(dp[i - 1][j])
        if j:
            for kk in range(3):
                dp[i][j][kk] = max(dp[i][j][kk], dp[i][j - 1][kk])
        for k in range(3, 0, -1):
            dp[i][j][k] = max(dp[i][j][k], dp[i][j][k - 1] + grid[i][j])



print(max(dp[r - 1][c - 1]))

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


def read_matrix(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter, xor, add
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right
from functools import reduce


class Top3:
    def __init__(self, ls=[0, 0, 0]):
        self.ls = sorted(ls, reverse=True)[:3]

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

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

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

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

R, C, K = ints()
RCV = read_tuple(K)
values = defaultdict(lambda: 0)
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(R):
    dp[i][0] = values[i, 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 = 0
        # print(top3.ls)
        left = dp[i][j - 1] + values[i, j] - \
            top3.append(values[i, j])  # top3を考慮した横のスコア
        # left = dp[i][j - 1] + values[i, j]

        # もしtopが大きければtop3は採用しない
        if top >= left:
            dp[i][j] = top
            top3 = Top3()
        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
input = sys.stdin.buffer.readline

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

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

    for r in range(R):
        for c in range(C):
            for n in range(4):
                if dp[c+1][r][n] > dp[c+1][r+1][0]:
                    dp[c+1][r+1][0] = dp[c+1][r][n]
                if dp[c+1][r][n] + State[c][r] > dp[c+1][r+1][1]:
                    dp[c+1][r+1][1] = dp[c+1][r][n] + State[c][r]
            for n in range(3):
                if dp[c][r+1][n] > dp[c+1][r+1][n]:
                    dp[c+1][r+1][n] = dp[c][r+1][n]
                if dp[c][r+1][n] + State[c][r] > dp[c+1][r+1][n+1]:
                    dp[c+1][r+1][n+1] = dp[c][r+1][n] + State[c][r]
        
    print(max(dp[C][R]))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
H, W, K = map(int, input().split())
a = [tuple(map(int, input().split())) for _ in range(K)]
dp = [0] * (H * W * 4)
table = [0] * (H * W)
for i, j, v in a: table[(i - 1) * W + j - 1] = v
for i in range(H):
  for j in range(W):
    x = i * W + j
    for k in range(4):
      if i + 1 < H:
        y = (i + 1) * W + j
        dp[y * 4 + 0] = max(dp[y * 4 + 0], dp[x * 4 + k])
      if j + 1 < W:
        y = i * W + j + 1
        dp[y * 4 + k] = max(dp[y * 4 + k], dp[x * 4 + k])
      if k + 1 <= 3 and table[x]:
        if i + 1 < H:
          y = (i + 1) * W + j
          dp[y * 4 + 0] = max(dp[y * 4 + 0], dp[x * 4 + k] + table[x])
        if j + 1 < W:
          y = i * W + j + 1
          dp[y * 4 + k + 1] = max(dp[y * 4 + k + 1], dp[x * 4 + k] + table[x])
for k in range(3): dp[(H * W - 1) * 4 + k] += table[-1]
print(max(dp[-4: -1]))

Submission status: Wrong Answer

Solution code:
import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")
from heapq import heappop, heappush

def getlist():
	return list(map(int, input().split()))

#処理内容
def main():
	R, C, K = getlist()
	items = [[0] * C for i in range(R)]
	for i in range(K):
		r, c, v = getlist()
		r -= 1; c -= 1
		items[r][c] = v

	DP = [[[-INF] * 4 for i in range(C)] for j in range(R)]
	# 初期
	if items[0][0] != 0:
		DP[0][0][0] = 0
		DP[0][0][1] = items[0][0]

	for r in range(1, R):
		DP[r][0][0] = 0
		DP[r][0][1] = DP[r - 1][0][1] + items[r][0]

	for c in range(1, C):
		DP[0][c][0] = DP[0][c - 1][0]
		for itr in range(1, 4):
			DP[0][c][itr] = max(DP[0][c - 1][itr - 1] + items[0][c], DP[0][c - 1][itr])

	for r in range(1, R):
		for c in range(1, C):
			prev = max(DP[r - 1][c])
			DP[r][c][0] = max(DP[r][c - 1][0], prev)
			DP[r][c][1] = max(DP[r][c - 1][0], prev) + items[r][c]
			for itr in range(2, 4):
				DP[r][c][itr] =  max(DP[r][c - 1][itr - 1] + items[r][c], DP[r][c - 1][itr])

	ans = max(DP[-1][-1])
	print(ans)


if __name__ == '__main__':
	main()

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import numpy as np
import itertools

def main():
    R, C, K = map(int, input().split())
    matrix = np.zeros((R, C))
    for k in range(K):
        r_i, c_i, v_i = map(int, input().split())
        matrix[r_i-1, c_i-1] = v_i
    
    dp = np.zeros((4, R, C))
    for r, c in itertools.product(range(R), range(C)):
        if r == 0:
            dp[0, r, c] = 0
            dp[1, r, c] = max(matrix[r, c], dp[1, r, c-1])
            dp[2, r, c] = max(dp[1, r, c-1] + matrix[r, c], dp[2, r, c-1])
            dp[3, r, c] = max(dp[2, r, c-1] + matrix[r, c], dp[3, r, c-1])
        else:
            dp[0, r, c] = max([dp[0, r, c-1], dp[0, r-1, c], dp[1, r-1, c], dp[2, r-1, c], dp[3, r-1, c]])
            dp[1, r, c] = max([dp[0, r, c-1] + matrix[r, c], dp[1, r, c-1], dp[0, r-1, c] + matrix[r, c], dp[1, r-1, c] + matrix[r, c], dp[2, r-1, c] + matrix[r, c], dp[3, r-1, c] + matrix[r, c]])
            dp[2, r, c] = max(dp[1, r, c-1] + matrix[r, c], dp[2, r, c-1])
            dp[3, r, c] = max(dp[2, r, c-1] + matrix[r, c], dp[3, r, c-1])
    print(int(max([dp[0, R-1, C-1], dp[1, R-1, C-1], dp[2, R-1, C-1], dp[3, R-1, C-1]])))
    
main()

Submission status: Wrong Answer

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


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

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

for r in range(R):
    for c in range(C):
        for n in range(4):
            dp[c+1][r+1][0] = max(dp[c+1][r+1][0], dp[c+1][r][n])
            dp[c+1][r+1][1] = max(dp[c+1][r+1][1], dp[c+1][r][n] + State[c][r])
        for n in range(3):
            dp[c+1][r+1][n] = max(dp[c+1][r+1][n], dp[c][r+1][n])
            dp[c+1][r+1][n+1] = max(dp[c+1][r+1][n+1], dp[c][r+1][n] + State[c][r])
    
print(max(dp[C][R]))

Submission status: Wrong Answer

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

r,c,k = map(int,input().split())
C = [list(map(int,input().split())) for i in range(k)]

I = [[0] * c for i in range(r)]
for i in range(k):
    I[C[i][0]-1][C[i][1]-1] = C[i][2]
# print(I)
D = [[[0] * 4 for i in range(c)] for j in range(r)]

for i in range(r):
    for j in range(c):
        D[i][j][1] = I[i][j]

for i in range(r):
    for j in range(c):
        for l in range(1,4):
            aa = 0
            if i-1 >= 0:
                aa = max(aa,max(D[i-1][j][0],D[i-1][j][1],D[i-1][j][2],D[i-1][j][3]) + I[i][j])
            if j-1 >= 0:
                aa = max(aa,D[i][j-1][l-1] + I[i][j], D[i][j-1][l])
            D[i][j][l] = max(D[i][j][l],aa)
# print(D)
ans = 0
for i in range(3):
    ans = max(ans, D[-1][-1][i])
print(ans)

Submission status: Wrong Answer

Solution code:
R, C, K = list(map(int,input().split()))
v = [[0 for _ in range(C)] for _ in range(R)]
for i in range(K):  
    in1, in2, in3 = list(map(int,input().split()))
    v[in1 - 1][in2 - 1] = in3

dp = [[[0 for _ in range(4)] for _ in range(C)] for _ in range(R)]
dp[0][0][0] = 0
dp[0][0][1] = v[0][0]
dp[0][0][2] = v[0][0]
dp[0][0][3] = v[0][0]

for i in range(1, R):
    dp[i][0][3] = max(dp[i - 1][0][3], dp[i - 1][0][2] + v[i][0])
    dp[i][0][2] = max(dp[i - 1][0][2], dp[i - 1][0][1] + v[i][0])
    dp[i][0][1] = max(dp[i - 1][0][1], dp[i - 1][0][0] + v[i][0])
    dp[i][0][0] = dp[i - 1][0][0]
    
for i in range(1, C):
    dp[0][i][3] = max(dp[0][i - 1][3], dp[0][i - 1][2] + v[0][i])
    dp[0][i][2] = max(dp[0][i - 1][2], dp[0][i - 1][1] + v[0][i])
    dp[0][i][1] = max(dp[0][i - 1][1], dp[0][i - 1][0] + v[0][i])
    dp[0][i][0] = dp[0][i - 1][0]

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

Submission status: Wrong Answer

Solution code:
# pypy

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



dp = [[[0]*4 for c in range(C)] for r in range(R)]
def get(r, c, k):
    try:
        return dp[r][c][k]
    except:
        return 0

for r in range(R):
    for c in range(C):
        dp[r][c][0] = max(get(r, c-1, 0), get(r-1, c, 0), get(r-1, c, 1), get(r-1, c, 2), get(r-1, c, 3))
        if (r, c) in rc2v:
            for k in range(1, 4):
                dp[r][c][k] = max(dp[r][c][k], get(r, c-1, k), get(r, c-1, k-1)+rc2v[(r, c)])
            dp[r][c][1] = max(dp[r][c][1], max(get(r-1, c, 0), get(r-1, c, 1), get(r-1, c, 2), get(r-1, c, 3))+rc2v[(r, c)])
        else:
            for k in range(1, 4):
                dp[r][c][k] = max(dp[r][c][k], get(r, c-1, k))

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