Problem:


Score : 500 points

Problem Statement

We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.

The square (i, j) has two numbers A_{ij} and B_{ij} written on it.

First, for each square, Takahashi paints one of the written numbers red and the other blue.

Then, he travels from the square (1, 1) to the square (H, W). In one move, he can move from a square (i, j) to the square (i+1, j) or the square (i, j+1). He must not leave the grid.

Let the unbalancedness be the absolute difference of the sum of red numbers and the sum of blue numbers written on the squares along Takahashi's path, including the squares (1, 1) and (H, W).

Takahashi wants to make the unbalancedness as small as possible by appropriately painting the grid and traveling on it.

Find the minimum unbalancedness possible.

Constraints

2 \leq H \leq 80

2 \leq W \leq 80

0 \leq A_{ij} \leq 80

0 \leq B_{ij} \leq 80

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W
A_{11} A_{12} \ldots A_{1W}
:
A_{H1} A_{H2} \ldots A_{HW}
B_{11} B_{12} \ldots B_{1W}
:
B_{H1} B_{H2} \ldots B_{HW}

Output

Print the minimum unbalancedness possible.

Sample Input 1

2 2
1 2
3 4
3 4
2 1

Sample Output 1

0

By painting the grid and traveling on it as shown in the figure below, the sum of red numbers and the sum of blue numbers are 3+3+1=7 and 1+2+4=7, respectively, for the unbalancedness of 0.

Sample Input 2

2 3
1 10 80
80 10 1
1 2 3
4 5 6

Sample Output 2

2



Sample input:
2 2
1 2
3 4
3 4
2 1


Sample output:
0

Submission status: Time Limit Exceeded

Solution code:
def main():
    import os
    import sys
    from io import BytesIO, IOBase
    
    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")
    mod = 10**9 + 7


            

    h, w = map(int, input().split())
    a = [[int(x) for x in input().split()] for _ in range(h)]
    b = [[int(x) for x in input().split()] for _ in range(h)]
    c = [[0]*w for _ in range(h)]
    max_value = 80 * (h + w)
    for i in range(h):
        for j in range(w):
            c[i][j] = abs(a[i][j] - b[i][j])
    dp = [[[False]*(max_value + 1) for _ in range(w)] for _ in range(h)]
    dp[0][0][c[0][0]] = True
    for i in range(h):
        for j in range(w):
            for k in range(max_value + 1):
                # print(i, j, k, k + c[i][j + 1])
                if 0 <= i + 1 < h and dp[i][j][k]:
                    if 0 <= k + c[i + 1][j] <= max_value:
                        dp[i + 1][j][k + c[i + 1][j]] = True
                    if 0 <= abs(k - c[i + 1][j]) <= max_value:
                        dp[i + 1][j][abs(k - c[i + 1][j])] = True
                if 0 <= j + 1 < w and dp[i][j][k]:
                    if 0 <= k + c[i][j + 1] <= max_value:
                        dp[i][j + 1][k + c[i][j + 1]] = True
                    if 0 <= abs(k - c[i][j + 1]) <= max_value:
                        dp[i][j + 1][abs(k - c[i][j + 1])] = True
    for k in range(max_value + 1):
        if dp[h - 1][w - 1][k]:
            print(k)
            sys.exit()
main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import os
    import sys
    from io import BytesIO, IOBase
    
    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")
    mod = 10**9 + 7


            

    h, w = map(int, input().split())
    a = [[int(x) for x in input().split()] for _ in range(h)]
    b = [[int(x) for x in input().split()] for _ in range(h)]
    c = [[0]*w for _ in range(h)]
    for i in range(h):
        for j in range(w):
            c[i][j] = abs(a[i][j] - b[i][j])
    dp = [[[False]*(80 * (h + w) + 1) for _ in range(w)] for _ in range(h)]
    dp[0][0][c[0][0]] = True
    for i in range(h):
        for j in range(w):
            for k in range(80 * (h + w) + 1):
                # print(i, j, k, k + c[i][j + 1])
                if 0 <= i + 1 < h:
                    if 0 <= k + c[i + 1][j] <= 80 * (h + w):
                        dp[i + 1][j][k + c[i + 1][j]] = dp[i][j][k] or dp[i + 1][j][k + c[i + 1][j]]
                    if 0 <= abs(k - c[i + 1][j]) <= 80 * (h + w):
                        dp[i + 1][j][abs(k - c[i + 1][j])] = dp[i][j][k] or dp[i + 1][j][abs(k - c[i + 1][j])]
                if 0 <= j + 1 < w:
                    if 0 <= k + c[i][j + 1] <= 80 * (h + w):
                        dp[i][j + 1][k + c[i][j + 1]] = dp[i][j][k] or dp[i][j + 1][k + c[i][j + 1]]
                    if 0 <= abs(k - c[i][j + 1]) <= 80 * (h + w):
                        dp[i][j + 1][abs(k - c[i][j + 1])] = dp[i][j][k] or dp[i][j + 1][abs(k - c[i][j + 1])]
    for k in range(80 * (h + w) + 1):
        if dp[h - 1][w - 1][k]:
            print(k)
            sys.exit()
main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

h, w = map(int, input().split())
a = [[int(x) for x in input().split()] for _ in range(h)]
b = [[int(x) for x in input().split()] for _ in range(h)]
c = [[0]*w for _ in range(h)]
for i in range(h):
    for j in range(w):
        c[i][j] = abs(a[i][j] - b[i][j])
dp = [[[False]*(80 * (h + w) + 1) for _ in range(w)] for _ in range(h)]
dp[0][0][c[0][0]] = True
for i in range(h):
    for j in range(w):
        for k in range(80 * (h + w) + 1):
            # print(i, j, k, k + c[i][j + 1])
            if 0 <= i + 1 < h:
                if 0 <= k + c[i + 1][j] <= 80 * (h + w):
                    dp[i + 1][j][k + c[i + 1][j]] = dp[i][j][k] or dp[i + 1][j][k + c[i + 1][j]]
                if 0 <= abs(k - c[i + 1][j]) <= 80 * (h + w):
                    dp[i + 1][j][abs(k - c[i + 1][j])] = dp[i][j][k] or dp[i + 1][j][abs(k - c[i + 1][j])]
            if 0 <= j + 1 < w:
                if 0 <= k + c[i][j + 1] <= 80 * (h + w):
                    dp[i][j + 1][k + c[i][j + 1]] = dp[i][j][k] or dp[i][j + 1][k + c[i][j + 1]]
                if 0 <= abs(k - c[i][j + 1]) <= 80 * (h + w):
                    dp[i][j + 1][abs(k - c[i][j + 1])] = dp[i][j][k] or dp[i][j + 1][abs(k - c[i][j + 1])]
for k in range(80 * (h + w) + 1):
    if dp[h - 1][w - 1][k]:
        print(k)
        sys.exit()

Submission status: Time Limit Exceeded

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

h,w = map(int,readline().split())
a = []
A = [list(map(int,readline().split())) for _ in range(h)]
B = [list(map(int,readline().split())) for _ in range(h)]
C = [[False]*w for _ in range(h)]
for i in range(h):
    for j in range(w):
        C[i][j] = abs(A[i][j] - B[i][j])

dp = [[set() for _ in range(w)] for _ in range(h)]
dp[0][0].add(C[0][0])

for i in range(h):
  for j in range(w):
    for k in dp[i][j]:
        if i < h-1:
          c = C[i+1][j]
          if k+c < 6321:
            dp[i+1][j].add(k+c)
          dp[i+1][j].add(abs(k-c))
        if j < w-1:
          d = C[i][j+1]
          if k+d < 6321:
            dp[i][j+1].add(k+d)
          dp[i][j+1].add(abs(k-d))

print(min(dp[h-1][w-1]))

Submission status: Time Limit Exceeded

Solution code:
# 経路の数は、(79 + 2) C 79 = 2^79
import numpy as np

import sys
readline = sys.stdin.readline

H,W = map(int,readline().split())
A = [None] * H
for i in range(H):
  A[i] = list(map(int,readline().split()))
  
B = [None] * H
for i in range(H):
  B[i] = list(map(int,readline().split()))

M = 0
C = [[0] * W for i in range(H)]
for i in range(H):
  for j in range(W):
    C[i][j] = abs(A[i][j] - B[i][j])
    M += C[i][j]
C = np.array(C, dtype = int)
del A
del B


# dp[(i,j)] = マスi,jで発生しうる偏り（set型）
from numba import njit,i8
@njit
def solve(H,W,M,C):
  dp = [[[False] * (M + 1) for j in range(W)] for i in range(H)]
  dp[0][0][C[0][0]] = True
  for i in range(H):
    for j in range(W):
      val = C[i][j]
      if i > 0:
        for k in range(len(dp[i - 1][j])):
          if dp[i - 1][j][k]:
            dp[i][j][k + val] = True
            dp[i][j][abs(k - val)] = True
      if j > 0:
        for k in range(len(dp[i][j - 1])):
          if dp[i][j - 1][k]:
            dp[i][j][k + val] = True
            dp[i][j][abs(k - val)] = True
        
  for k in range(len(dp[-1][-1])):
    if dp[-1][-1][k]:
      return k

print(solve(H,W,M,C))

Submission status: Time Limit Exceeded

Solution code:
H,W=map(int,input().split())
red=[]
blue=[]
for i in range(H):
  A=list(map(int,input().split()))
  red.append(A)
for i in range(H):
  B=list(map(int,input().split()))
  blue.append(B)
list=[[[0 for i in range(80*(j+k+1)+1)] for j in range(W)] for k in range(H)]
list[0][0][abs(red[0][0]-blue[0][0])]=1
for i in range(H):
  for j in range(W):
    for k in range(len(list[i][j])):
      if list[i][j][k]==1:
        if i+1<H:
          if abs(k-abs(red[i+1][j]-blue[i+1][j]))<=80*(i+j+2): 
            list[i+1][j][abs(k-abs(red[i+1][j]-blue[i+1][j]))]=1
          if abs(k+abs(red[i+1][j]-blue[i+1][j]))<=80*(i+j+2): 
            list[i+1][j][abs(k+abs(red[i+1][j]-blue[i+1][j]))]=1
        if j+1<W:
          if abs(k-abs(red[i][j+1]-blue[i][j+1]))<=80*(i+j+2): 
            list[i][j+1][abs(k-abs(red[i][j+1]-blue[i][j+1]))]=1
          if abs(k+abs(red[i][j+1]-blue[i][j+1]))<=80*(i+j+2): 
            list[i][j+1][abs(k+abs(red[i][j+1]-blue[i][j+1]))]=1           
for i in range(12801):
  if list[H-1][W-1][i]==1:
    print(i)
    break

Submission status: Time Limit Exceeded

Solution code:
H,W=map(int,input().split())
red=[]
blue=[]
for i in range(H):
  A=list(map(int,input().split()))
  red.append(A)
for i in range(H):
  B=list(map(int,input().split()))
  blue.append(B)
list=[[[0 for i in range(12801)] for j in range(W)] for k in range(H)]
list[0][0][abs(red[0][0]-blue[0][0])]=1
for i in range(H):
  for j in range(W):
    for k in range(12801):
      if list[i][j][k]==1:
        if i+1<H:
          if abs(k-abs(red[i+1][j]-blue[i+1][j]))<12801: 
            list[i+1][j][abs(k-abs(red[i+1][j]-blue[i+1][j]))]=1
          if abs(k+abs(red[i+1][j]-blue[i+1][j]))<12801: 
            list[i+1][j][abs(k+abs(red[i+1][j]-blue[i+1][j]))]=1
        if j+1<W:
          if abs(k-abs(red[i][j+1]-blue[i][j+1]))<12801: 
            list[i][j+1][abs(k-abs(red[i][j+1]-blue[i][j+1]))]=1
          if abs(k+abs(red[i][j+1]-blue[i][j+1]))<12801: 
            list[i][j+1][abs(k+abs(red[i][j+1]-blue[i][j+1]))]=1           
for i in range(12801):
  if list[H-1][W-1][i]==1:
    print(i)
    break

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.buffer.readline

h, w = map(int, input().split())
AA = [list(map(int, input().split())) for _ in range(h)]
BB = [list(map(int, input().split())) for _ in range(h)]

kouho = [[set() for _ in range(w)] for _ in range(h)]

delta = AA[0][0] - BB[0][0]
kouho[0][0].add(delta)
kouho[0][0].add(-delta)
dx = [1, 0]
dy = [0, 1]
for y in range(h):
    for x in range(w):
        for d in range(2):
            nx = x + dx[d]
            ny = y + dy[d]
            if nx < 0 or nx >= w or ny < 0 or ny >= h:
                continue
            delta = AA[ny][nx] - BB[ny][nx]
            for num in kouho[y][x]:
                if 80 * (h + w) >= abs(num + delta):
                    kouho[ny][nx].add(abs(num + delta))
                if 80 * (h + w) >= abs(num - delta):
                    kouho[ny][nx].add(abs(num - delta))
ans = 10 ** 10
for a in kouho[h - 1][w - 1]:
    ans = min(ans, abs(a))
print(ans)

Submission status: Time Limit Exceeded

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

h, w = map(int, input().split())
AA = [list(map(int, input().split())) for _ in range(h)]
BB = [list(map(int, input().split())) for _ in range(h)]

kouho = [[set() for _ in range(w)] for _ in range(h)]

delta = AA[0][0] - BB[0][0]
kouho[0][0].add(delta)
kouho[0][0].add(-delta)
dx = [1, 0]
dy = [0, 1]
for y in range(h):
    for x in range(w):
        for d in range(2):
            nx = x + dx[d]
            ny = y + dy[d]
            if nx < 0 or nx >= w or ny < 0 or ny >= h:
                continue
            delta = AA[ny][nx] - BB[ny][nx]
            for num in kouho[y][x]:
                temp = ((h + w - 2) - (ny + nx) + 1) * 80
                if temp >= abs(num + delta):
                    kouho[ny][nx].add(num + delta)
                if temp >= abs(num - delta):
                    kouho[ny][nx].add(num - delta)
ans = 10 ** 10
for a in kouho[h - 1][w - 1]:
    ans = min(ans, abs(a))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, input().split())
AA = [list(map(int, input().split())) for _ in range(h)]
BB = [list(map(int, input().split())) for _ in range(h)]

kouho = [[set() for _ in range(w)] for _ in range(h)]

delta = AA[0][0] - BB[0][0]
kouho[0][0].add(delta)
kouho[0][0].add(-delta)
dx = [1, 0]
dy = [0, 1]
for y in range(h):
    for x in range(w):
        for d in range(2):
            nx = x + dx[d]
            ny = y + dy[d]
            if nx < 0 or nx >= w or ny < 0 or ny >= h:
                continue
            delta = AA[ny][nx] - BB[ny][nx]
            for num in kouho[y][x]:
                temp = ((h + w - 2) - (ny + nx) + 1) * 80
                if temp >= abs(num + delta):
                    kouho[ny][nx].add(num + delta)
                if temp >= abs(num - delta):
                    kouho[ny][nx].add(num - delta)
ans = 10 ** 10
for a in kouho[h - 1][w - 1]:
    ans = min(ans, abs(a))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    h, w = map(int, input().split())
    grid = [[0] * (w + 1)]
    for _ in range(h):
        grid.append([0] + list(map(int, input().split())))
    for i in range(1, h + 1):
        l = [0] + list(map(int, input().split()))
        for j in range(w + 1):
            grid[i][j] = abs(grid[i][j] - l[j])

    biggest = max([max(i) for i in grid])
    m = (h + w) * biggest

    if m == 0:
        print(0)
        exit()

    unba = [[[False] * m for _ in range(w + 1)] for _ in range(h + 1)]
    # trueplace = [[[] for _ in range(w + 1)] for _ in range(h + 1)]

    for i in range(1, w + 1):
        unba[0][i][0] = True
    for i in range(1, h + 1):
        unba[i][0][0] = True

    for i in range(1, h + 1):
        for j in range(1, w + 1):
            for k in range(m):
                if unba[i-1][j][k] or unba[i][j-1][k]:
                    unba[i][j][grid[i][j] + k] = True
                    unba[i][j][abs(grid[i][j] - k)] = True

    l = [i for i in range(m) if unba[h][w][i]]
    print(min(l))

main()

Submission status: Time Limit Exceeded

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

def solve():
    maxV = 12800

    H, W = map(int, input().split())
    Ass = [tuple(map(int, input().split())) for _ in range(H)]
    Bss = [tuple(map(int, input().split())) for _ in range(H)]

    dp = [[[0]*(2*maxV+1) for j in range(W)] for i in range(H)]
    diff = abs(Ass[0][0] - Bss[0][0])
    dp[0][0][diff+maxV] = dp[0][0][-diff+maxV] = 1
    for i in range(H):
        for j in range(W):
            diff = abs(Ass[i][j] - Bss[i][j])
            if i > 0:
                dp0 = dp[i-1][j]
                dpij = dp[i][j]
                for k in range(diff, 2*maxV+1):
                    if dp0[k]:
                        dpij[k-diff] = 1
                for k in range(2*maxV+1-diff):
                    if dp0[k]:
                        dpij[k+diff] = 1
            if j > 0:
                dp0 = dp[i][j-1]
                dpij = dp[i][j]
                for k in range(diff, 2*maxV+1):
                    if dp0[k]:
                        dpij[k-diff] = 1
                for k in range(2*maxV+1-diff):
                    if dp0[k]:
                        dpij[k+diff] = 1

    ans = maxV
    dpHW = dp[-1][-1]
    for k in range(2*maxV+1):
        if dpHW[k]:
            j = abs(k-maxV)
            if j < ans:
                ans = j

    print(ans)


solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
def main():
  input=sys.stdin.readline
  h,w=map(int,input().split())
  a=[list(map(int,input().split())) for _ in range(h)]
  b=[list(map(int,input().split())) for _ in range(h)]
  m=80*(h+w)
  dp=[[[False]*(m+1) for i in range(w)] for j in range(h)]
  dp[0][0][abs(a[0][0]-b[0][0])]=True
  for i in range(h):
    for j in range(w):
      for k in range(m+1):
        if dp[i][j][k]:
          if i<h-1:
            if abs(k+a[i+1][j]-b[i+1][j])<=m:
              dp[i+1][j][abs(k+a[i+1][j]-b[i+1][j])]=True
            if abs(k+b[i+1][j]-a[i+1][j])<=m:
              dp[i+1][j][abs(k+b[i+1][j]-a[i+1][j])]=True
          if j<w-1:
            if abs(k+a[i][j+1]-b[i][j+1])<=m:
              dp[i][j+1][abs(k+a[i][j+1]-b[i][j+1])]=True
            if abs(k+b[i][j+1]-a[i][j+1])<=m:
              dp[i][j+1][abs(k+b[i][j+1]-a[i][j+1])]=True
  for i in range(m+1):
    if dp[h-1][w-1][i]:
      return print(i)
if __name__=='__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
# 経路の数は、(79 + 2) C 79 = 2^79

import sys
readline = sys.stdin.readline

H,W = map(int,readline().split())
A = [None] * H
for i in range(H):
  A[i] = list(map(int,readline().split()))
  
B = [None] * H
for i in range(H):
  B[i] = list(map(int,readline().split()))

M = 0
C = [[0] * W for i in range(H)]
for i in range(H):
  for j in range(W):
    C[i][j] = abs(A[i][j] - B[i][j])
    M += C[i][j]
del A
del B
# dp[(i,j)] = マスi,jで発生しうる偏り（set型）
dp = [[[False] * (M + 1) for j in range(W)] for i in range(H)]
dp[0][0][C[0][0]] = True
for i in range(H):
  for j in range(W):
    val = C[i][j]
    if i > 0:
      for k in range(len(dp[i - 1][j])):
        if dp[i - 1][j][k]:
          dp[i][j][k + val] = True
          dp[i][j][abs(k - val)] = True
    if j > 0:
      for k in range(len(dp[i][j - 1])):
        if dp[i][j - 1][k]:
          dp[i][j][k + val] = True
          dp[i][j][abs(k - val)] = True
      
for k in range(len(dp[-1][-1])):
  if dp[-1][-1][k]:
    print(k)
    break

Submission status: Time Limit Exceeded

Solution code:
# 経路の数は、(79 + 2) C 79 = 2^79

import sys
readline = sys.stdin.readline

H,W = map(int,readline().split())
A = [None] * H
for i in range(H):
  A[i] = list(map(int,readline().split()))
  
B = [None] * H
for i in range(H):
  B[i] = list(map(int,readline().split()))

M = 0
C = [[0] * W for i in range(H)]
for i in range(H):
  for j in range(W):
    C[i][j] = abs(A[i][j] - B[i][j])
    M += C[i][j]
del A
del B
# dp[(i,j)] = マスi,jで発生しうる偏り（set型）
from collections import defaultdict
dp = defaultdict(set)
dp[(0,0)].add(C[0][0])
for i in range(H):
  for j in range(W):
    val = C[i][j]
    if i > 0:
      for s in dp[(i - 1,j)]:
        if s + val <= M // 2:
          dp[(i,j)].add(s + val)
        dp[(i,j)].add(abs(s - val))
      del dp[(i - 1,j)]
    if j > 0:
      for s in dp[(i,j - 1)]:
        if s + val <= M // 2:
          dp[(i,j)].add(s + val)
        dp[(i,j)].add(abs(s - val))
      
print(min(dp[(H - 1,W - 1)]))

Submission status: Time Limit Exceeded

Solution code:
# 経路の数は、(79 + 2) C 79 = 2^79

import sys
readline = sys.stdin.readline

H,W = map(int,readline().split())
A = [None] * H
for i in range(H):
  A[i] = list(map(int,readline().split()))
  
B = [None] * H
for i in range(H):
  B[i] = list(map(int,readline().split()))

M = 0
C = [[0] * W for i in range(H)]
for i in range(H):
  for j in range(W):
    C[i][j] = abs(A[i][j] - B[i][j])
    M += C[i][j]
del A
del B
# dp[(i,j)] = マスi,jで発生しうる偏り（set型）
from collections import defaultdict
dp = defaultdict(set)
dp[(0,0)].add(C[0][0])
for i in range(H):
  for j in range(W):
    val = C[i][j]
    if i > 0:
      for s in dp[(i - 1,j)]:
        if s + val <= M:
          dp[(i,j)].add(s + val)
        dp[(i,j)].add(abs(s - val))
      del dp[(i - 1,j)]
    if j > 0:
      for s in dp[(i,j - 1)]:
        if s + val <= M:
          dp[(i,j)].add(s + val)
        dp[(i,j)].add(abs(s - val))
      
print(min(dp[(H - 1,W - 1)]))

Submission status: Time Limit Exceeded

Solution code:
# 経路の数は、(79 + 2) C 79 = 2^79

import sys
readline = sys.stdin.readline

H,W = map(int,readline().split())
A = [None] * H
for i in range(H):
  A[i] = list(map(int,readline().split()))
  
B = [None] * H
for i in range(H):
  B[i] = list(map(int,readline().split()))

# dp[(i,j)] = マスi,jで発生しうる偏り（set型）
from collections import defaultdict
dp = defaultdict(set)
dp[(0,0)].add(abs(A[0][0] - B[0][0]))
for i in range(H):
  for j in range(W):
    val = abs(A[i][j] - B[i][j])
    if i > 0:
      for s in dp[(i - 1,j)]:
        if s + val < (H - i + W - j) * 80:
          dp[(i,j)].add(s + val)
        dp[(i,j)].add(abs(s - val))
      del dp[(i - 1,j)]
    if j > 0:
      for s in dp[(i,j - 1)]:
        if s + val < (H - i + W - j) * 80:
          dp[(i,j)].add(s + val)
        dp[(i,j)].add(abs(s - val))
      
print(min(dp[(H - 1,W - 1)]))

Submission status: Time Limit Exceeded

Solution code:
# 経路の数は、(79 + 2) C 79 = 2^79

import sys
readline = sys.stdin.readline

H,W = map(int,readline().split())
A = [None] * H
for i in range(H):
  A[i] = list(map(int,readline().split()))
  
B = [None] * H
for i in range(H):
  B[i] = list(map(int,readline().split()))

# dp[(i,j)] = マスi,jで発生しうる偏り（set型）
from collections import defaultdict
dp = defaultdict(set)
dp[(0,0)].add(abs(A[0][0] - B[0][0]))
for i in range(H):
  for j in range(W):
    val = abs(A[i][j] - B[i][j])
    if i > 0:
      for s in dp[(i - 1,j)]:
        dp[(i,j)].add(s + val)
        dp[(i,j)].add(abs(s - val))
      del dp[(i - 1,j)]
    if j > 0:
      for s in dp[(i,j - 1)]:
        dp[(i,j)].add(s + val)
        dp[(i,j)].add(abs(s - val))
      
print(min(dp[(H - 1,W - 1)]))

Submission status: Time Limit Exceeded

Solution code:
# 経路の数は、(79 + 2) C 79 = 2^79

import sys
readline = sys.stdin.readline

H,W = map(int,readline().split())
A = [None] * H
for i in range(H):
  A[i] = list(map(int,readline().split()))
  
B = [None] * H
for i in range(H):
  B[i] = list(map(int,readline().split()))

C = [[0] * W for i in range(H)]
for i in range(H):
  for j in range(W):
    C[i][j] = abs(A[i][j] - B[i][j])
    
# dp[(i,j)] = マスi,jで発生しうる偏り（set型）
from collections import defaultdict
dp = defaultdict(set)
dp[(0,0)].add(C[0][0])
for i in range(H):
  for j in range(W):
    if i > 0:
      for s in dp[(i - 1,j)]:
        dp[(i,j)].add(s + C[i][j])
        dp[(i,j)].add(abs(s - C[i][j]))
      del dp[(i - 1,j)]
    if j > 0:
      for s in dp[(i,j - 1)]:
        dp[(i,j)].add(s + C[i][j])
        dp[(i,j)].add(abs(s - C[i][j]))
      
print(min(dp[(H - 1,W - 1)]))

Submission status: Time Limit Exceeded

Solution code:
# 経路の数は、(79 + 2) C 79 = 2^79

import sys
readline = sys.stdin.readline

H,W = map(int,readline().split())
A = [None] * H
for i in range(H):
  A[i] = list(map(int,readline().split()))
  
B = [None] * H
for i in range(H):
  B[i] = list(map(int,readline().split()))

C = [[0] * W for i in range(H)]
for i in range(H):
  for j in range(W):
    C[i][j] = abs(A[i][j] - B[i][j])
    
# dp[(i,j)] = マスi,jで発生しうる偏り（set型）
from collections import defaultdict
dp = defaultdict(set)
dp[(0,0)].add(C[0][0])
for i in range(H):
  for j in range(W):
    if i > 0:
      for s in dp[(i - 1,j)]:
        dp[(i,j)].add(s + C[i][j])
        dp[(i,j)].add(abs(s - C[i][j]))
      
    if j > 0:
      for s in dp[(i,j - 1)]:
        dp[(i,j)].add(s + C[i][j])
        dp[(i,j)].add(abs(s - C[i][j]))
      
print(min(dp[(H - 1,W - 1)]))

Submission status: Time Limit Exceeded

Solution code:
# 経路の数は、(79 + 2) C 79 = 2^79

import sys
readline = sys.stdin.readline

H,W = map(int,readline().split())
A = [None] * H
for i in range(H):
  A[i] = list(map(int,readline().split()))
  
B = [None] * H
for i in range(H):
  B[i] = list(map(int,readline().split()))

C = [[0] * W for i in range(H)]
for i in range(H):
  for j in range(W):
    C[i][j] = abs(A[i][j] - B[i][j])
    
# dp[i][j] = マスi,jで発生しうる偏り（set型）
dp = [[set() for j in range(W)] for i in range(H)]
dp[0][0].add(C[0][0])
for i in range(H):
  for j in range(W):
    if i > 0:
      for s in dp[i - 1][j]:
        dp[i][j].add(s + C[i][j])
        dp[i][j].add(abs(s - C[i][j]))
    if j > 0:
      for s in dp[i][j - 1]:
        dp[i][j].add(s + C[i][j])
        dp[i][j].add(abs(s - C[i][j]))
      
print(min(dp[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
def main():
    # import sys
    # readline = sys.stdin.readline
    # readlines = sys.stdin.readlines
    H, W = map(int, input().split())
    A = [list(map(int, input().split())) for _ in range(H)]
    B = [list(map(int, input().split())) for _ in range(H)]
    grid = [[0] * W for _ in range(H)]
    for i in range(H):
        for j in range(W):
            grid[i][j] = abs(A[i][j] - B[i][j])

    dp = [[set() for _ in range(W)] for _ in range(H)]
    dp[0][0].add(grid[0][0])

    for i in range(H):
        for j in range(W):
            for k in dp[i][j]:
                if i < H - 1:
                    nk = grid[i + 1][j]
                    dp[i + 1][j].add(k + nk)
                    dp[i + 1][j].add(abs(k - nk))
                if j < W - 1:
                    nk = grid[i][j + 1]
                    dp[i][j + 1].add(k + nk)
                    dp[i][j + 1].add(abs(k - nk))

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(H)]
B = [list(map(int, input().split())) for _ in range(H)]
grid = [[0] * W for _ in range(H)]
for i in range(H):
    for j in range(W):
        grid[i][j] = abs(A[i][j] - B[i][j])

dp = [[set() for _ in range(W)] for _ in range(H)]
dp[0][0].add(grid[0][0])

for i in range(H):
    for j in range(W):
        for k in dp[i][j]:
            if i < H - 1:
                nk = grid[i + 1][j]
                dp[i + 1][j].add(k + nk)
                dp[i + 1][j].add(abs(k - nk))
            if j < W - 1:
                nk = grid[i][j + 1]
                dp[i][j + 1].add(k + nk)
                dp[i][j + 1].add(abs(k - nk))

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

Submission status: Time Limit Exceeded

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

H, W = map(int, input().split())
A = [list(map(int, input().split())) for i in range(H)]
B = [list(map(int, input().split())) for i in range(H)]
D = [[0]*W for i in range(H)]
mx = 1
for i in range(H):
    for j in range(W):
        D[i][j] = abs(A[i][j]-B[i][j])
        mx = max(mx, D[i][j])
MX = mx*(H+W)
dp = [[[0]*(MX+1) for _ in range(W+1)] for _ in range(H+1)]
dp[1][1][D[0][0]] = 1
for i in range(1,H+1):
    for j in range(1,W+1):
        for k in range(MX+1):
            if dp[i][j][k]:
                if j+1 <= W:
                    d = D[i-1][j]
                    if k+d <= MX:
                        dp[i][j+1][k+d] = 1
                    dp[i][j+1][abs(k-d)] = 1
                if i+1 <= H:
                    d = D[i][j-1]
                    if k+d <= MX:
                        dp[i+1][j][k+d] = 1
                    dp[i+1][j][abs(k-d)] = 1
#for i in range(H+1):
#    for j in range(W+1):
#        print(i, j)
#        print(dp[i][j])
for i in range(MX+1):
    if dp[H][W][i]:
        print(i)
        exit()