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: Runtime Error

Solution code:
#!usr/bin/env python3
import sys
def LI(): return [int(x) for x in sys.stdin.readline().split()]

def solve():
    h,w,k = LI()
    S = h*w
    if w == 1:
        d = [h]
    else:
        d = [h,1]
    s = [0]*S
    for _ in range(k):
        y,x,v = LI()
        y -= 1
        x -= 1
        s[y*w+x] = v
    dp = [[-float("inf")]*4 for _ in range(S)]
    dp[0][0] = 0
    sc = s[0]
    if sc != 0:
        dp[0][1] = sc
    for i in range(S-1):
        for n in range(4):
            dyx = dp[i][n]
            for ind,di in enumerate(d):
                if not ind and i+w >= S:
                    continue
                elif ind and i%w == w-1 or w == 1:
                    continue
                j = i+di
                if not ind:
                    nn = 0
                else:
                    nn = n
                if dp[j][nn] < dyx:
                    dp[j][nn] = dyx
                if nn < 3:
                    nsc = s[j]
                    if nsc != 0:
                        nn += 1
                        ndp = dyx+nsc
                        if dp[j][nn] < ndp:
                            dp[j][nn] = ndp
    print(max(dp[-1]))
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Runtime Error

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    
    r, c, k = map(int, input().split())
    tizu = [[0 for _ in range(c)] for _ in range(r)]
    for _ in range(k):
        rr, cc, v = map(int, input().split())
        tizu[rr - 1][cc - 1] = v
        
    dp = [[0, 0, 0, 0] for _ in range(r)]
    dp[0][1] = tizu[0][0]
    
    for i in range(r):
        for j in range(c):
            if i != 0:
                tmp = max(dp[j])
                dp[j][0] = tmp
                dp[j][1] = tmp + tizu[i][j]
                dp[j][2] = 0
                dp[j][3] = 0
            if j != 0:
                dp[j][0] = max(dp[j][0], dp[j - 1][0])
                dp[j][1] = max(dp[j][1], dp[j - 1][1], dp[j - 1][0] + tizu[i][j])
                dp[j][2] = max(dp[j - 1][2], dp[j - 1][1] + tizu[i][j])
                dp[j][3] = max(dp[j - 1][3], dp[j - 1][2] + tizu[i][j])
    print(max(dp[-1]))
    
main()

Submission status: Runtime Error

Solution code:
r,c,k=list(map(int,input().split()))
m=[[0 for i in range(c)]for j in range(r)]
for i in range(k):
  inp=list(map(int,input().split()))
  m[inp[0]-1][inp[1]-1]=inp[2]
d=[[0 for i in range(3)] for i in range(c+1)]
nd=[[0 for i in range(3)] for i in range(c+1)]
for i in range(r):
  for j in range(c):
    for k in range(1,3):
      d[j][k]=max(d[j-1][k-1]+m[i][j],d[j-1][k],d[j][k])
    mm=d[j-1][2]+m[i][j]
    nd[j-1][0]=max(nd[j-2][0],mm)
    nd[j-1][1]=max(nd[j-2][1],mm)
    nd[j-1][2]=max(nd[j-2][2],mm)
  d=nd
print(d[-3][0])

Submission status: Runtime Error

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
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)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    h,w,k = LI()
    S = h*w
    d = [h,1]
    s = [0]*S
    for _ in range(k):
        y,x,v = LI()
        y -= 1
        x -= 1
        s[y*w+x] = v
    dp = [[-float("inf")]*4 for _ in range(S)]
    dp[0][0] = 0
    sc = s[0]
    if sc != 0:
        dp[0][1] = sc
    for i in range(S-1):
        for n in range(4):
            dyx = dp[i][n]
            for ind,di in enumerate(d):
                if not ind and i+w > S:
                    continue
                elif ind and i%w == w-1:
                    continue
                j = i+di
                if not ind:
                    nn = 0
                else:
                    nn = n
                if dp[j][nn] < dyx:
                    dp[j][nn] = dyx
                if nn < 3:
                    nsc = s[j]
                    if nsc != 0:
                        nn += 1
                        ndp = dyx+nsc
                        if dp[j][nn] < ndp:
                            dp[j][nn] = ndp
    print(max(dp[-1]))
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Runtime Error

Solution code:
r,c,k=list(map(int,input().split()))
m=[[0 for i in range(c)]for j in range(r)]
for i in range(k):
  inp=list(map(int,input().split()))
  m[inp[0]-1][inp[1]-1]=inp[2]
d=[[0 for i in range(3)] for i in range(c+1)]

for i in range(r):
  nd=[[0 for i in range(3)] for i in range(c+1)]
  for j in range(c):
    for k in range(1,3):
      d[j][k]=max(d[j-1][k-1]+m[i][j],d[j-1][k],d[j][k])
    nd[j-1][0]=max(nd[j-2][0],d[j-1][2]+m[i][j])
    nd[j-1][1]=max(nd[j-2][1],d[j-1][2]+m[i][j])
    nd[j-1][2]=max(nd[j-2][2],d[j-1][2]+m[i][j])
  d=nd
print(d[-3][0])

Submission status: Runtime Error

Solution code:
"""
    Satwik_Tiwari ;) .
    14th AUGUST , 2020  - FRIDAY
"""

#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function

from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================
#fast I/O region
BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
  def wrapped_func(*args, **kwargs):
    if stack: return f(*args, **kwargs)
    to = f(*args, **kwargs)
    while True:
      if type(to) is GeneratorType:
        stack.append(to)
        to = next(to)
        continue
      stack.pop()
      if not stack: break
      to = stack[-1].send(to)
    return to
  return wrapped_func
#### END ITERATE RECURSION ####

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for p in range(t):
        solve()
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
    res = 1     # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) : # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1      # y = y/2
        x = (x * x) % p
    return res
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))
dp = [[[-1 for i in range(4)]for j in range(3002)] for k in range(3002)]

def rec(grid,i,j,taken):
    if(i==len(grid) or j==len(grid[0])):
        return 0
    if(dp[i][j][taken]!=-1):
        return dp[i][j][taken]

    temp1 =0
    temp2 =0

    if(taken<3):
        temp1 = grid[i][j]+max(rec(grid,i+1,j,0),rec(grid,i,j+1,taken+1))
    temp2 = max(rec(grid,i+1,j,0),rec(grid,i,j+1,taken))

    dp[i][j][taken] =  max(temp1,temp2)
    return dp[i][j][taken]

def solve():
    r,c,k = sep()

    grid = [[0 for i in range(c)]for j in range(r)]
    for i in range(k):
        a,b,c = sep()
        a-=1
        b-=1
        print(a,b,c)
        grid[a][b] = c

    print(rec(grid,0,0,0))










testcase(1)
# testcase(int(inp()))