Working out (Codeforces 429B)
Tags: DP, dp

Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column.Iahub starts with workout located at line 1 and column 1. He needs to finish with workout a[n][m]. After finishing workout a[i][j], he can go to workout a[i + 1][j] or a[i][j + 1]. Similarly, Iahubina starts with workout a[n][1] and she needs to finish with workout a[1][m]. After finishing workout from cell a[i][j], she goes to either a[i][j + 1] or a[i - 1][j]. There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout.If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs.

Input: The first line of the input contains two integers n and m (3 ≤ n, m ≤ 1000). Each of the next n lines contains m integers: j-th number from i-th line denotes element a[i][j] (0 ≤ a[i][j] ≤ 105).

Output: The output contains a single number — the maximum total gain possible. 

Note: Iahub will choose exercises a[1][1] → a[1][2] → a[2][2] → a[3][2] → a[3][3]. Iahubina will choose exercises a[3][1] → a[2][1] → a[2][2] → a[2][3] → a[1][3].

Sample Inputs:
3 3
100 100 100
100 1 100
100 100 100

Sample Outputs:
800

Solution (Python):
import os, sys
from io import BytesIO, IOBase

def main():
    (n, m) = map(int, input().split())
    arr = [list(map(int, input().split())) for _ in range(n)]
    dp1 = [[0] * (m + 2) for _ in range(n + 2)]
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            dp1[i][j] = max(dp1[i - 1][j], dp1[i][j - 1]) + arr[i - 1][j - 1]
    dp2 = [[0] * (m + 2) for _ in range(n + 2)]
    for i in range(1, n + 1):
        for j in range(m, 0, -1):
            dp2[i][j] = max(dp2[i - 1][j], dp2[i][j + 1]) + arr[i - 1][j - 1]
    dp3 = [[0] * (m + 2) for _ in range(n + 2)]
    for i in range(n, 0, -1):
        for j in range(m, 0, -1):
            dp3[i][j] = max(dp3[i + 1][j], dp3[i][j + 1]) + arr[i - 1][j - 1]
    dp4 = [[0] * (m + 2) for _ in range(n + 2)]
    for i in range(n, 0, -1):
        for j in range(1, m + 1):
            dp4[i][j] = max(dp4[i + 1][j], dp4[i][j - 1]) + arr[i - 1][j - 1]
    maxi = 0
    for i in range(2, n):
        for j in range(2, m):
            maxi = max(maxi, dp1[i][j - 1] + dp4[i + 1][j] + dp2[i - 1][j] + dp3[i][j + 1], dp1[i - 1][j] + dp4[i][j - 1] + dp2[i][j + 1] + dp3[i + 1][j])
    print(maxi)
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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
if __name__ == '__main__':
    main()

Solution (Python):
import sys, os
from io import BytesIO, IOBase
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
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')
(stdin, stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
    return stdin.readline().strip()

def iinp():
    return int(inp())

def out(var, end='\n'):
    stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
    stdout.write(' '.join(map(str, var)) + end)

def lmp():
    return list(mp())

def mp():
    return map(int, inp().split())

def l1d(n, val=0):
    return [val for i in range(n)]

def l2d(n, m, val=0):
    return [l1d(m, val) for j in range(n)]

def ceil(a, b):
    return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
    if x <= 1:
        return False
    if x in (2, 3):
        return True
    if x % 2 == 0:
        return False
    for i in range(3, int(sqrt(x)) + 1, 2):
        if x % i == 0:
            return False
    return True
(n, m) = mp()
mat = [lmp() for i in range(n)]
dp1 = l2d(n + 1, m + 1)
dp2 = l2d(n + 1, m + 1)
dp3 = l2d(n + 1, m + 1)
dp4 = l2d(n + 1, m + 1)
for i in range(1, n + 1):
    for j in range(1, m + 1):
        dp1[i][j] = max(dp1[i - 1][j], dp1[i][j - 1]) + mat[i - 1][j - 1]
for i in range(n - 1, -1, -1):
    for j in range(m - 1, -1, -1):
        dp2[i][j] = max(dp2[i + 1][j], dp2[i][j + 1]) + mat[i][j]
for i in range(n - 1, -1, -1):
    for j in range(1, m + 1):
        dp3[i][j] = max(dp3[i + 1][j], dp3[i][j - 1]) + mat[i][j - 1]
for i in range(1, n + 1):
    for j in range(m - 1, -1, -1):
        dp4[i][j] = max(dp4[i - 1][j], dp4[i][j + 1]) + mat[i - 1][j]
mx = 0
for i in range(1, n - 1):
    for j in range(1, m - 1):
        mx = max(mx, dp1[i][j + 1] + dp2[i + 1][j] + dp3[i][j] + dp4[i + 1][j + 1], dp1[i + 1][j] + dp2[i][j + 1] + dp3[i + 1][j + 1] + dp4[i][j])
print(mx)

Solution (Python):
import os
import sys
from io import BytesIO, IOBase

def main():
    (n, m) = map(int, input().split())
    arr = []
    for _ in range(n):
        arr.append(list(map(int, input().split())))
    dp1 = [[0 for _ in range(m + 2)] for _ in range(n + 2)]
    dp2 = [[0 for _ in range(m + 2)] for _ in range(n + 2)]
    dp3 = [[0 for _ in range(m + 2)] for _ in range(n + 2)]
    dp4 = [[0 for _ in range(m + 2)] for _ in range(n + 2)]
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            dp1[i][j] = arr[i - 1][j - 1] + max(dp1[i - 1][j], dp1[i][j - 1])
    for i in range(n, 0, -1):
        for j in range(1, m + 1):
            dp2[i][j] = arr[i - 1][j - 1] + max(dp2[i + 1][j], dp2[i][j - 1])
    for i in range(n, 0, -1):
        for j in range(m, 0, -1):
            dp3[i][j] = arr[i - 1][j - 1] + max(dp3[i + 1][j], dp3[i][j + 1])
    for i in range(1, n + 1):
        for j in range(m, 0, -1):
            dp4[i][j] = arr[i - 1][j - 1] + max(dp4[i - 1][j], dp4[i][j + 1])
    ans = 0
    for r in range(2, n):
        for c in range(2, m):
            ans = max(ans, max(dp1[r][c - 1] + dp2[r + 1][c] + dp3[r][c + 1] + dp4[r - 1][c], dp1[r - 1][c] + dp2[r][c - 1] + dp3[r + 1][c] + dp4[r][c + 1]))
    print(ans)
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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
if __name__ == '__main__':
    main()