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:
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, [])]*(C+1) for _ in range(R+1)]
for r in range(R):
    for c in range(C):
        w, m = dp[r][c]
        if (r+1) < R:
            if dp[r+1][c][0] <= w+g[r][c]:
                dp[r+1][c] = (w+g[r][c], [])
        if (c+1) < C:
            if dp[r][c+1][0] <= w+g[r][c]:
                if len(m) < 2:
                    m.append(g[r][c])
                    m.sort()
                    dp[r][c+1] = (w+g[r][c], m)
                else:
                    tw = w+g[r][c]-min(m[0], g[r][c])
                    if dp[r][c+1][0] < tw:
                        m = m[1:]
                        m.append(g[r][c])
                        m.sort()
                        dp[r][c+1] = (tw, m)

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

Submission status: Wrong Answer

Solution code:
import sys

input = sys.stdin.readline
R, C, K = map(int, input().split())
rcv = [tuple(map(int, input().split())) for _ in range(K)]
values = [[0]*C for _ in range(R)]
for r, c, v in rcv:
    values[r-1][c-1] = v

dp = [[[0]*4 for _ in range(C)] for _ in range(R+1)] # [r, c, とったアイテム]のvの最大値

for r in range(R-1, -1, -1):
    dp[r][C - 1][0] = dp[r + 1][C - 1][3]
    for i in range(1, 4):
        dp[r][C-1][i] = dp[r + 1][C-1][3]+values[r][C-1]
    for c in range(C-2, -1, -1):
        v = values[r][c]
        for i in range(4):
            if i == 0:
                dp[r][c][i] = max([dp[r+1][c][3], dp[r][c+1][i]])
            else:
                dp[r][c][i] = max([dp[r + 1][c][3], dp[r][c + 1][i], dp[r][c + 1][i-1] + v])
print(dp[0][0][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, [])]*(C+1) for _ in range(R+1)]
for r in range(R):
    for c in range(C):
        w, m = dp[r][c]
        if (r+1) < R:
            if dp[r+1][c][0] <= w+g[r][c]:
                dp[r+1][c] = (w+g[r][c], [])
        if (c+1) < C:
            if dp[r][c+1][0] <= w+g[r][c]:
                if len(m) < 2:
                    m.append(g[r][c])
                    m.sort()
                    dp[r][c+1] = (w+g[r][c], m)
                else:
                    tw = w+g[r][c]-min(m[0], g[r][c])
                    if dp[r][c+1][0] < tw:
                        m = [g[r][c]]+m[1:]
                        dp[r][c+1] = (tw, m)

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

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


import sys
sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(R, C, K, RCV):

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

    memo = [[[0] * 4 for _ in range(C)] for __ in range(R)]
    def f(i, j, p):
        if i >= R or j >= C:
            return 0

        print(i, j, p)
        if memo[i][j][p] != 0:
            return memo[i][j][p]

        r = 0
        r = max(r, f(i+1, j, 0))
        r = max(r, f(i, j+1, p))
        if V[i][j] != 0 and p < 3:
            r = max(r, f(i+1, j, 0) + V[i][j])
            r = max(r, f(i, j+1, p+1) + V[i][j])
        memo[i][j][p] = r
        return r
    return f(0, 0, 0)


def main():
    R, C, K = read_int_n()
    RCV = [read_int_n() for _ in range(K)]
    print(slv(R, C, K, RCV))


if __name__ == '__main__':
    main()

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, [])]*(C+1) for _ in range(R+1)]
for r in range(R):
    for c in range(C):
        w, m = dp[r][c]
        if (r+1) < R:
            if dp[r+1][c][0] < w+g[r][c]:
                dp[r+1][c] = (w+g[r][c], [])
        if (c+1) < C:
            if dp[r][c+1][0] < w+g[r][c]:
                if len(m) < 2:
                    m.append(g[r][c])
                    m.sort()
                    dp[r][c+1] = (w+g[r][c], m)
                else:
                    tw = w+g[r][c]-min(m[0], g[r][c])
                    if dp[r][c+1][0] < tw:
                        m = [g[r][c]]+m[1:]
                        dp[r][c+1] = (tw, m)

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

Submission status: Wrong Answer

Solution code:
"""
dp[i][j]　=> i行目j列目がゴールの場合の最大値
dp[i][j] => 
"""

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

#0行目を初期化する
memo = [0,0,0]

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

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

for i in range(1,R):
    memo = [0,0,0]
    heapq.heapify(memo)
    for j in range(C):
        v = items[i][j]
        if j != 0:
            #左から入る場合の価値を求める。
            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[-1][-1])

Submission status: Wrong Answer

Solution code:
R, C, K = map(int, input().split())
rcvs = [tuple(map(int, input().split())) for _ in range(K)]

rcvs.sort(key = lambda t: t[1] * 30000 + t[0])

dp = [[0] * (R+1) for _ in range(4)]
index = 0
for c in range(C+1):
    while index < K and rcvs[index][1] == c:
        x, _, v = rcvs[index]
        if dp[3][x] < dp[2][x] + v:
            dp[3][x] = dp[2][x] + v
        if dp[2][x] < dp[1][x] + v:
            dp[2][x] = dp[1][x] + v
        if dp[1][x] < dp[0][x] + v:
            dp[1][x] = dp[0][x] + v
        if x < R and dp[0][x+1] < max((dp[i][x] + v for i in range(4))):
            dp[0][x+1] = max((dp[i][x] + v for i in range(4)))
        index += 1
        #print(dp)   
    
print(max(max(row) for row in dp))

Submission status: Wrong Answer

Solution code:
(r,c,_),*d = [list(map(int, s.split())) for s in open(0)]

dp = [[0] * 4 for _ in range(r+1)]
d = sorted(d, key=lambda x:(x[1], x[0]))
for i, _, v in d:
    i -= 1
    if i > 0:
        dp[i][0] = max([dp[i][0]] + max(dp[:i]))
    for j in range(3):
        dp[i][3-j] = max(dp[i][3-j], dp[i][2-j] + v)
print(max(max(dp)))

Submission status: Wrong Answer

Solution code:
import sys
# import heapq, functools, collections
# import math, random
# from collections import Counter, defaultdict

# available on Google, not available on Codeforces
import numpy as np
# import scipy


def solve(items,R,C):  # fix inputs here
    console("----- solving ------")
    console(R,C)

    grid = np.array([[0 for _ in range(C)] for _ in range(R)])

    for r,c,v in items:
        grid[r-1][c-1] = v

    # console(np.array(grid))  # PLEASE SILENCE
    console("\n\n")

    dp = np.array([[[0 for _ in range(4)] for _ in range(C)] for _ in range(R)])

    if grid[0][0] > 0:
        dp[0][0][1] = dp[0][0][0] + grid[0][0]

    for i in range(1,R):
        dp[i][0][0] = max(dp[i-1][0][0], dp[i-1][0][1])
        if grid[i][0] > 0:
            dp[i][0][1] = dp[i][0][0] + grid[i][0]

    for j in range(1,C):
        for k in range(1,4):
            dp[0][j][k] = max(dp[0][j-1][k], dp[0][j-1][k-1] + grid[0][j])

    # console(np.array(dp)[:,:,0])  # PLEASE SILENCE
    # console(np.array(dp)[:,0,:])  # PLEASE SILENCE
    # console(np.array(dp)[0,:,:])  # PLEASE SILENCE
    # console(np.array(dp))  # PLEASE SILENCE
    # console("\n\nPost")

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

    # console(np.array(dp)[:,:,0])  # PLEASE SILENCE
    # console(np.array(dp)[:,:,1])  # PLEASE SILENCE
    # console(np.array(dp)[:,:,2])  # PLEASE SILENCE
    # console(np.array(dp)[:,:,3])  # PLEASE SILENCE
    # console(np.array(dp))  # PLEASE SILENCE

    # return a string (i.e. not a list or matrix)
    return max(dp[R-1][C-1][k] for k in range(4))


def console(*args):  # the judge will not read these print statement
    # print('\033[36m', *args, '\033[0m', file=sys.stderr)
    return

# fast read all
inn = sys.stdin.readlines()

for case_num in [1]:
    # read line as a string
    # strr = input()

    # read line as an integer
    # k = int(input())
    
    # read one line and parse each word as a string
    # lst = input().split()

    # read one line and parse each word as an integer
    r,c,nrows = list(map(int,inn[0].split()))

    # read matrix and parse as integers (after reading read nrows)
    # lst = list(map(int,input().split()))
    # nrows = lst[0]  # index containing information, please change
    grid = []
    for t in range(1,nrows+1):
        grid.append(list(map(int,inn[t].split())))

    res = solve(grid,r,c)  # please change
    
    # Google - case number required
    # print("Case #{}: {}".format(case_num+1, res))

    # Codeforces - no case number required
    print(res)

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

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)


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


'''
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を次も継続して使う

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

Submission status: Wrong Answer

Solution code:
import sys
# import heapq, functools, collections
# import math, random
# from collections import Counter, defaultdict

# available on Google, not available on Codeforces
import numpy as np
# import scipy


def solve(items,R,C):  # fix inputs here
    console("----- solving ------")
    console(R,C)

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

    for r,c,v in items:
        grid[r-1][c-1] = v

    # console(np.array(grid))  # PLEASE SILENCE
    console("\n\n")

    dp = np.array([[[0 for _ in range(4)] for _ in range(C)] for _ in range(R)])

    if grid[0][0] > 0:
        dp[0][0][1] = dp[0][0][0] + grid[0][0]

    for i in range(1,R):
        dp[i][0][0] = max(dp[i-1][0][0], dp[i-1][0][1])
        if grid[i][0] > 0:
            dp[i][0][1] = dp[i][0][0] + grid[i][0]

    for j in range(1,C):
        for k in range(1,4):
            dp[0][j][k] = max(dp[0][j-1][k], dp[0][j-1][k-1] + grid[0][j])

    # console(np.array(dp)[:,:,0])  # PLEASE SILENCE
    # console(np.array(dp)[:,0,:])  # PLEASE SILENCE
    # console(np.array(dp)[0,:,:])  # PLEASE SILENCE
    # console(np.array(dp))  # PLEASE SILENCE
    # console("\n\nPost")

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

    # console(np.array(dp)[:,:,0])  # PLEASE SILENCE
    # console(np.array(dp)[:,:,1])  # PLEASE SILENCE
    # console(np.array(dp)[:,:,2])  # PLEASE SILENCE
    # console(np.array(dp)[:,:,3])  # PLEASE SILENCE
    # console(np.array(dp))  # PLEASE SILENCE

    # return a string (i.e. not a list or matrix)
    return max(dp[R-1][C-1][k] for k in range(4))


def console(*args):  # the judge will not read these print statement
    # print('\033[36m', *args, '\033[0m', file=sys.stderr)
    return

# fast read all
inn = sys.stdin.readlines()

for case_num in [1]:
    # read line as a string
    # strr = input()

    # read line as an integer
    # k = int(input())
    
    # read one line and parse each word as a string
    # lst = input().split()

    # read one line and parse each word as an integer
    r,c,nrows = list(map(int,inn[0].split()))

    # read matrix and parse as integers (after reading read nrows)
    # lst = list(map(int,input().split()))
    # nrows = lst[0]  # index containing information, please change
    grid = []
    for t in range(1,nrows+1):
        grid.append(list(map(int,inn[t].split())))

    res = solve(grid,r,c)  # please change
    
    # Google - case number required
    # print("Case #{}: {}".format(case_num+1, res))

    # Codeforces - no case number required
    print(res)

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

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)


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)
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を次も継続して使う

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, [])]*(C+1) for _ in range(R+1)]
for r in range(R):
    for c in range(C):
        w, m = dp[r][c]
        if (r+1) < R:
            if dp[r+1][c][0] < w+g[r][c]:
                dp[r+1][c] = (w+g[r][c], [])
        if (c+1) < C:
            if dp[r][c+1][0] < w+g[r][c]:
                if len(m) < 2:
                    m.append(g[r][c])
                    dp[r][c+1] = (w+g[r][c], m)
                else:
                    m.append(g[r][c])
                    m.sort()
                    tw = w+g[r][c]-m[0]
                    if dp[r][c+1][0] < tw:
                        dp[r][c+1] = (tw, m[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())
V = [[0]*C for _ in range(R)]
for _ in range(K):
    r, c, v = map(int, input().split())
    V[r-1][c-1] = v
dp = [[0]*4 for _ in range(C+1)]
for j in range(C):
    for k in range(1, 4):
        dp[j+1][k] = max(dp[j][k-1]+V[0][j], dp[j][k])
for i in range(1, R):
    newdp = [[0]*4 for _ in range(C+1)]
    for j in range(C):
        newdp[j+1][0] = max(max(dp[j+1]), newdp[j][0])
        newdp[j+1][1] = max(max(dp[j+1]), newdp[j][0])+V[i][j]
        for k in range(2, 4):
            newdp[j+1][k] = max(newdp[j][k-1]+V[i][j], newdp[j][k])
    dp = newdp
print(max(dp[-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, [])]*(C+1) for _ in range(R+1)]
for r in range(R):
    for c in range(C):
        if g[r][c] <= 0:
            continue
        w, m = dp[r][c]
        if (r+1) < R:
            if dp[r+1][c][0] < w+g[r][c]:
                dp[r+1][c] = (w+g[r][c], [])
        if (c+1) < C:
            if dp[r][c+1][0] < w+g[r][c]:
                if len(m) < 2:
                    m.append(g[r][c])
                    dp[r][c+1] = (w+g[r][c], m)
                else:
                    m.append(g[r][c])
                    m.sort()
                    tw = w+g[r][c]-m[0]
                    if dp[r][c+1][0] < tw:
                        dp[r][c+1] = (tw, m[1:])

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

Submission status: Wrong Answer

Solution code:
# pypy
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
from collections import defaultdict
import gc

R, C, K = map(int, readline().split())
rcv = list(map(int, read().split()))
rr = rcv[::3]
cc = rcv[1::3]
vv = rcv[2::3]
rc2v = defaultdict(int)
for _r, _c, _v in zip(rr, cc, vv):
    rc2v[(_r-1, _c-1)] = _v

del rcv, rr, cc, vv
gc.collect()


dp = [[[0]*4 for c in range(C)] for r in range(2)]
dp[0][0][1] = rc2v[(0, 0)]

for c in range(1, C):
    for k in range(1, 4):
        dp[0][c][k] = max(dp[0][c-1][k], dp[0][c-1][k-1]+rc2v[(0, c)])

for r in range(1, R):
    rr = r % 2
    dp[rr][0][0] = max(dp[rr-1][0])
    if (r, 0) in rc2v:
        dp[rr][0][1] = max(dp[rr-1][0]) + rc2v[(r, 0)]

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

if R % 2:
    print(max(dp[0][-1]))
else:
    print(max(dp[1][-1]))

Submission status: Wrong Answer

Solution code:
import sys

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


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

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

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

    print(dp[C])

    return


if __name__ == '__main__':
    main()

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

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] = max(dp[r][c-1][k], dp[r][c][k])
                if r != 0:
                    dp[r][c][0] = max(dp[r-1][c][k], dp[r][c][0])

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

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] * (C + 1) for _ in range(R + 1)] for _ in range(4)]
dp[0][0][0] = 0
for j in range(C):
    for i in range(R):
        for k in range(3):
            # Use
            if field[i][j] and k < 3:
                dp[k+1][i][j+1] = max(dp[k+1][i][j+1], dp[k][i][j] + field[i][j]) 
                dp[0][i+1][j] = max(dp[0][i+1][j], dp[k][i][j] + field[i][j]) 
            # No use down
            dp[0][i+1][j] = max(dp[0][i+1][j], dp[k][i][j]) 
            # No use right
            dp[k][i][j+1] = max(dp[k][i][j+1], dp[k][i][j]) 

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
R,C,K = map(int,input().split())
dp = [0 for _ in range(C+1)]
vl = [[0 for _ in range(C+1)] for f in range(R+1)]
ddc = defaultdict(lambda:0)

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

for j in range(1, R+1):
	sol = []
	for i in range(1, C+1):
		dp[i] = max(dp[i-1], dp[i])
		if vl[j][i] >= 1:
			targ = vl[j][i]
			#print(len(sol))
			if len(sol) < 3:
				dp[i] += targ
				sol.append(targ)
			else:
				minsol = min(sol)
				if minsol < targ:
					#print(sol)
					dp[i] += targ - minsol
					sol.remove(minsol)
					sol.append(targ)

print(dp[C])

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.buffer.readline
R,C,K = map(int,input().split())
goods = [[-1]*(C+1) for _ in range(R+1)]
INF = 10**16
for i in range(K):
    ri,ci,vi = map(int,input().split())
    goods[ri][ci] = vi
DP = [[[-INF,-INF,-INF,-INF] for _ in range(C+1)] for _ in range(R+1)]
DP[1][1][0] = 0
if goods[1][1] != -1:
    DP[1][1][1] = goods[1][1]
for j in range(1,C):
    DP[1][j+1][0] = 0
    if goods[1][j+1] != -1:
        for k in range(1,3):
            DP[1][j+1][k] = max(DP[1][j][k],DP[1][j][k-1]+goods[1][j+1])
    else:
        for k in range(1,3):
            DP[1][j+1][k] = DP[1][j][k]
for i in range(1,R):
    DP[i+1][1][0] = max(DP[i][1])
    if goods[i+1][1] != -1:
        DP[i+1][1][1] = DP[i+1][1][0] + goods[i+1][1]
for i in range(2,R+1):
    for j in range(2,C+1):
        DP[i][j][0] = max(max(DP[i-1][j]),DP[i][j-1][0])
        if goods[i][j] != -1:
            DP[i][j][1] = max(DP[i][j][0]+goods[i][j],DP[i][j-1][1])
            DP[i][j][2] = max(DP[i][j-1][2],DP[i][j-1][1]+goods[i][j])
            DP[i][j][3] = max(DP[i][j-1][3],DP[i][j-1][2]+goods[i][j])
        else:
            for i in range(1,3):
                DP[i][j][k] = DP[i][j-1][k]
print(max(DP[R][C]))