Explorer Space (Codeforces 1517D)
Tags: DP, shortest paths

You are wandering in the explorer space of the 2050 Conference.The explorer space can be viewed as an undirected weighted grid graph with size $$$n\times m$$$. The set of vertices is $$$\{(i, j)|1\le i\le n, 1\le j\le m\}$$$. Two vertices $$$(i_1,j_1)$$$ and $$$(i_2, j_2)$$$ are connected by an edge if and only if $$$|i_1-i_2|+|j_1-j_2|=1$$$.At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing $$$x$$$ exhibits, your boredness increases by $$$x$$$.For each starting vertex $$$(i, j)$$$, please answer the following question: What is the minimum possible boredness if you walk from $$$(i, j)$$$ and go back to it after exactly $$$k$$$ steps?You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex $$$(i, j)$$$ after $$$k$$$ steps, you can visit $$$(i, j)$$$ (or not) freely.

Input: The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2\leq n, m\leq 500, 1\leq k\leq 20$$$).The $$$j$$$-th number ($$$1\le j \le m - 1$$$) in the $$$i$$$-th line of the following $$$n$$$ lines is the number of exibits on the edge between vertex $$$(i, j)$$$ and vertex $$$(i, j+1)$$$. The $$$j$$$-th number ($$$1\le j\le m$$$) in the $$$i$$$-th line of the following $$$n-1$$$ lines is the number of exibits on the edge between vertex $$$(i, j)$$$ and vertex $$$(i+1, j)$$$. The number of exhibits on each edge is an integer between $$$1$$$ and $$$10^6$$$.

Output: Output $$$n$$$ lines with $$$m$$$ numbers each. The $$$j$$$-th number in the $$$i$$$-th line, $$$answer_{ij}$$$, should be the minimum possible boredness if you walk from $$$(i, j)$$$ and go back to it after exactly $$$k$$$ steps.If you cannot go back to vertex $$$(i, j)$$$ after exactly $$$k$$$ steps, $$$answer_{ij}$$$ should be $$$-1$$$. 

Note: In the first example, the answer is always $$$10$$$ no matter how you walk.In the second example, $$$answer_{21} = 10$$$, the path is $$$(2,1) \to (1,1) \to (1,2) \to (2,2) \to (2,1)$$$, the boredness is $$$4 + 1 + 2 + 3 = 10$$$.

Sample Inputs:
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1

2 2 4
1
3
4 2

2 2 3
1
2
3 4

Sample Outputs:
10 10 10
10 10 10
10 10 10

4 4
10 6

-1 -1
-1 -1

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

def main():
    max_int = 10 ** 9
    d = ((1, 0), (-1, 0), (0, 1), (0, -1))
    (n, m, k) = li_input()
    H = []
    for i in range(n):
        H.append(li_input() + [max_int])
    V = []
    for i in range(n - 1):
        V.append(li_input())
    V.append([max_int] * m)
    if k % 2:
        for i in range(n):
            print(' '.join(['-1'] * m))
        return
    k //= 2
    DP0 = [[0] * (m + 1) for _ in range(n + 1)]
    DP1 = [[0] * (m + 1) for _ in range(n + 1)]
    for kk in range(k):
        for i in range(n):
            for j in range(m):
                l = DP0[i][j - 1] + H[i][j - 1]
                r = DP0[i][j + 1] + H[i][j]
                u = DP0[i - 1][j] + V[i - 1][j]
                d = DP0[i + 1][j] + V[i][j]
                DP1[i][j] = min(l, r, u, d)
        (DP0, DP1) = (DP1, DP0)
    O = []
    for row in DP0[:-1]:
        O.append(' '.join((str(n * 2) for n in row[:-1])))
    print('\n'.join(O))
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):
    """"""
    (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()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
    return sys.stdin.readline().rstrip('\r\n')

def i_input():
    return int(input())

def l_input():
    return input().split()

def li_input():
    return list(map(int, l_input()))

def il_input():
    return list(map(int, l_input()))
if __name__ == '__main__':
    TT = time.time()
    main()

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

def main():
    (n, m, k) = map(int, input().split())
    left = [array('i', map(int, input().split())) for _ in range(n)]
    down = [array('i', map(int, input().split())) for _ in range(n - 1)]
    dp = [array('i', [-1 if k & 1 else 0 for _ in range(m)]) for _ in range(n)]
    if k & 1 == 0:
        for l in range(k // 2):
            dp1 = [array('i', [10 ** 8 for _ in range(m)]) for _ in range(n)]
            for i in range(n):
                for j in range(m):
                    if j > 0:
                        dp1[i][j] = min(dp1[i][j], dp[i][j - 1] + 2 * left[i][j - 1])
                    if j < m - 1:
                        dp1[i][j] = min(dp1[i][j], dp[i][j + 1] + 2 * left[i][j])
                    if i > 0:
                        dp1[i][j] = min(dp1[i][j], dp[i - 1][j] + 2 * down[i - 1][j])
                    if i < n - 1:
                        dp1[i][j] = min(dp1[i][j], dp[i + 1][j] + 2 * down[i][j])
            dp = dp1
    for i in dp:
        print(*i)
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 os
import sys
from io import BytesIO, IOBase

def main():
    (n, m, k) = map(int, input().split())
    left = [list(map(int, input().split())) for _ in range(n)]
    down = [list(map(int, input().split())) for _ in range(n - 1)]
    dp = [[-1 if k & 1 else 0 for _ in range(m)] for _ in range(n)]
    if k & 1 == 0:
        for l in range(k // 2):
            dp1 = [[10 ** 8 for _ in range(m)] for _ in range(n)]
            for i in range(n):
                for j in range(m):
                    if j > 0:
                        dp1[i][j] = min(dp1[i][j], dp[i][j - 1] + 2 * left[i][j - 1])
                    if j < m - 1:
                        dp1[i][j] = min(dp1[i][j], dp[i][j + 1] + 2 * left[i][j])
                    if i > 0:
                        dp1[i][j] = min(dp1[i][j], dp[i - 1][j] + 2 * down[i - 1][j])
                    if i < n - 1:
                        dp1[i][j] = min(dp1[i][j], dp[i + 1][j] + 2 * down[i][j])
            dp = dp1
    for i in dp:
        print(*i)
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()