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:
import sys

def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり

H,W = LI()
A = [[0]*(W+1)]+[[0]+LI() for i in range(H)]
B = [[0]*(W+1)]+[[0]+LI() for i in range(H)]
C = [[A[i][j]-B[i][j] for j in range(W+1)] for i in range(H+1)]

from collections import defaultdict

dp = defaultdict(set)

# dp[(i,j)] = (i,j)に至ったときに偏りとして有り得る数のset

dp[(1,1)] = {C[1][1],-C[1][1]}

for i in range(1,H+1):
    for j in range(1,W+1):
        if i != H and j != W:
            for k in dp[(i,j)]:
                dp[(i+1,j)].add(k+C[i+1][j])
                dp[(i+1,j)].add(k-C[i+1][j])
                dp[(i,j+1)].add(k+C[i][j+1])
                dp[(i,j+1)].add(k-C[i][j+1])
        elif i == H and j != W:
            for k in dp[(i,j)]:
                dp[(i,j+1)].add(k+C[i][j+1])
                dp[(i,j+1)].add(k-C[i][j+1])
        elif i != H and j == W:
            for k in dp[(i,j)]:
                dp[(i+1,j)].add(k+C[i+1][j])
                dp[(i+1,j)].add(k-C[i+1][j])
        else:
            continue

l = list(dp[(H,W)])
l = [abs(i) for i in l]
print(min(l))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
H, W = map(int, input().split())
red_map = np.array([input().split() for i in range(H)], dtype="int")
blue_map = np.array([input().split() for i in range(H)], dtype="int")
sub_map = abs(red_map - blue_map)
dp = [[[] for i in range(W)] for i in range(H)]

for i in range(H):
  for j in range(W):
    if not i and not j:
      dp[i][j].append(sub_map[i][j])
      dp[i][j].append(-sub_map[i][j])
    if i > 0 and j > 0:
      for k in dp[i-1][j]:
        dp[i][j].append(k + sub_map[i][j])
        dp[i][j].append(k - sub_map[i][j])
      for l in dp[i][j-1]:
        dp[i][j].append(l + sub_map[i][j])
        dp[i][j].append(l - sub_map[i][j])
    if i > 0 and not j:
      for m in dp[i-1][j]:
        dp[i][j].append(m + sub_map[i][j])
        dp[i][j].append(m - sub_map[i][j])
    if j > 0 and not i:
      for n in dp[i][j-1]:
        dp[i][j].append(n + sub_map[i][j])
        dp[i][j].append(n - sub_map[i][j])

print(min(np.abs(dp[H-1][W-1])))

Submission status: Time Limit Exceeded

Solution code:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

def main():
    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)]

    lst=[[0]*w for i in range(h)]

    lst[0][0]={abs(a[0][0]-b[0][0]):1}
    # print(lst)
    d=deque([(0,0)])
    while d:
        now=d.popleft()
        tmp=lst[now[0]][now[1]].keys()
        if now[0]+1<h:
            ab=abs(a[now[0]+1][now[1]]-b[now[0]+1][now[1]])
            if lst[now[0]+1][now[1]]==0:
                d.append((now[0]+1,now[1]))
                lst[now[0]+1][now[1]]={}

            for i in tmp:
                if not i+ab in lst[now[0]+1][now[1]]:
                    lst[now[0]+1][now[1]][i+ab]=1
                if not abs(i-ab) in lst[now[0]+1][now[1]]:
                    lst[now[0]+1][now[1]][abs(i-ab)]=1

        # print(lst)
        if now[1]+1<w:
            ab=abs(a[now[0]][now[1]+1]-b[now[0]][now[1]+1])
            if lst[now[0]][now[1]+1]==0:
                d.append((now[0],now[1]+1))
                lst[now[0]][now[1]+1]={}

            for i in tmp:
                if not i+ab in lst[now[0]][now[1]+1]:
                    lst[now[0]][now[1]+1][i+ab]=1
                if not abs(i-ab) in lst[now[0]][now[1]+1]:
                    lst[now[0]][now[1]+1][abs(i-ab)]=1
        # print(d)
        # print(lst)
    anslst=list(lst[-1][-1].keys())
    for i in range(10**9):
        if i in anslst:
            print(i)
            break

main()

Submission status: Time Limit Exceeded

Solution code:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

def main():
    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)]

    lst=[[0]*w for i in range(h)]

    lst[0][0]={abs(a[0][0]-b[0][0]):1}
    # print(lst)
    d=deque([(0,0)])
    while d:
        now=d.popleft()
        tmp=lst[now[0]][now[1]].keys()
        if now[0]+1<h:
            ab=abs(a[now[0]+1][now[1]]-b[now[0]+1][now[1]])
            if lst[now[0]+1][now[1]]==0:
                d.append((now[0]+1,now[1]))
                lst[now[0]+1][now[1]]={}

            for i in tmp:
                if not i+ab in lst[now[0]+1][now[1]]:
                    lst[now[0]+1][now[1]][i+ab]=1
                if not abs(i-ab) in lst[now[0]+1][now[1]]:
                    lst[now[0]+1][now[1]][abs(i-ab)]=1

        # print(lst)
        if now[1]+1<w:
            ab=abs(a[now[0]][now[1]+1]-b[now[0]][now[1]+1])
            if lst[now[0]][now[1]+1]==0:
                d.append((now[0],now[1]+1))
                lst[now[0]][now[1]+1]={}

            for i in tmp:
                if not i+ab in lst[now[0]][now[1]+1]:
                    lst[now[0]][now[1]+1][i+ab]=1
                if not abs(i-ab) in lst[now[0]][now[1]+1]:
                    lst[now[0]][now[1]+1][abs(i-ab)]=1
        # print(d)
        # print(lst)
    anslst=list(lst[-1][-1].keys())
    anslst.sort(key=lambda x: abs(x))
    print(abs(anslst[0]))

main()

Submission status: Time Limit Exceeded

Solution code:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

def main():
    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)]

    lst=[[0]*w for i in range(h)]

    lst[0][0]={abs(a[0][0]-b[0][0]):1}
    # print(lst)
    d=deque([(0,0)])
    while d:
        now=d.popleft()
        tmp=lst[now[0]][now[1]].keys()
        if now[0]+1<h:
            ab=abs(a[now[0]+1][now[1]]-b[now[0]+1][now[1]])
            if lst[now[0]+1][now[1]]==0:
                d.append((now[0]+1,now[1]))
                lst[now[0]+1][now[1]]={}

            for i in tmp:
                lst[now[0]+1][now[1]][i+ab]=1
                lst[now[0]+1][now[1]][abs(i-ab)]=1

        # print(lst)
        if now[1]+1<w:
            ab=abs(a[now[0]][now[1]+1]-b[now[0]][now[1]+1])
            if lst[now[0]][now[1]+1]==0:
                d.append((now[0],now[1]+1))
                lst[now[0]][now[1]+1]={}

            for i in tmp:
                lst[now[0]][now[1]+1][i+ab]=1
                lst[now[0]][now[1]+1][abs(i-ab)]=1
        # print(d)
        # print(lst)
    anslst=list(lst[-1][-1].keys())
    anslst.sort(key=lambda x: abs(x))
    print(abs(anslst[0]))

main()

Submission status: Time Limit Exceeded

Solution code:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]


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

lst=[[0]*w for i in range(h)]

lst[0][0]={abs(a[0][0]-b[0][0]):1}
# print(lst)
for i in range(h):
    for j in range(w):
            tmp=lst[i][j].keys()
            if i+1<h:
                if lst[i+1][j]==0:
                    lst[i+1][j]={}
                ab=abs(a[i+1][j]-b[i+1][j])
                for k in tmp:
                    lst[i+1][j][k+ab]=1
                    lst[i+1][j][abs(k-ab)]=1

            # print(lst)
            if j+1<w:
                if lst[i][j+1]==0:
                    lst[i][j+1]={}
                ab=abs(a[i][j+1]-b[i][j+1])
                for k in tmp:
                    lst[i][j+1][k+ab]=1
                    lst[i][j+1][abs(k-ab)]=1
    # print(d)
    # print(lst)
anslst=list(lst[-1][-1].keys())
anslst.sort(key=lambda x: abs(x))
print(abs(anslst[0]))

Submission status: Time Limit Exceeded

Solution code:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]


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

lst=[[0]*w for i in range(h)]

lst[0][0]={abs(a[0][0]-b[0][0]):1}
# print(lst)
d=deque([(0,0)])
while d:
    now=d.popleft()
    tmp=lst[now[0]][now[1]].keys()
    if now[0]+1<h:
        ab=abs(a[now[0]+1][now[1]]-b[now[0]+1][now[1]])
        if lst[now[0]+1][now[1]]==0:
            d.append((now[0]+1,now[1]))
            lst[now[0]+1][now[1]]={}

        for i in tmp:
            lst[now[0]+1][now[1]][i+ab]=1
            lst[now[0]+1][now[1]][abs(i-ab)]=1

    # print(lst)
    if now[1]+1<w:
        ab=abs(a[now[0]][now[1]+1]-b[now[0]][now[1]+1])
        if lst[now[0]][now[1]+1]==0:
            d.append((now[0],now[1]+1))
            lst[now[0]][now[1]+1]={}

        for i in tmp:
            lst[now[0]][now[1]+1][i+ab]=1
            lst[now[0]][now[1]+1][abs(i-ab)]=1
    # print(d)
    # print(lst)
anslst=list(lst[-1][-1].keys())
anslst.sort(key=lambda x: abs(x))
print(abs(anslst[0]))

Submission status: Time Limit Exceeded

Solution code:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]


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

lst=[[0]*w for i in range(h)]

lst[0][0]={abs(a[0][0]-b[0][0]):1}
# print(lst)
d=deque([(0,0)])
while d:
    now=d.popleft()
    if now[0]+1<h:
        ab=abs(a[now[0]+1][now[1]]-b[now[0]+1][now[1]])
        if lst[now[0]+1][now[1]]==0:
            d.append((now[0]+1,now[1]))
            lst[now[0]+1][now[1]]={}

        for i in lst[now[0]][now[1]].keys():
            lst[now[0]+1][now[1]][i+ab]=1
            lst[now[0]+1][now[1]][abs(i-ab)]=1

    # print(lst)
    if now[1]+1<w:
        ab=abs(a[now[0]][now[1]+1]-b[now[0]][now[1]+1])
        if lst[now[0]][now[1]+1]==0:
            d.append((now[0],now[1]+1))
            lst[now[0]][now[1]+1]={}

        for i in lst[now[0]][now[1]].keys():
            lst[now[0]][now[1]+1][i+ab]=1
            lst[now[0]][now[1]+1][abs(i-ab)]=1
    # print(d)
    # print(lst)
anslst=list(lst[-1][-1].keys())
anslst.sort(key=lambda x: abs(x))
print(abs(anslst[0]))

Submission status: Time Limit Exceeded

Solution code:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]


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

lst=[[0]*w for i in range(h)]

lst[0][0]={abs(a[0][0]-b[0][0]):1}
# print(lst)
d=deque([(0,0)])
while d:
    now=d.popleft()
    if now[0]+1<h:
        if lst[now[0]+1][now[1]]==0:
            d.append((now[0]+1,now[1]))
            lst[now[0]+1][now[1]]={}

        for i in lst[now[0]][now[1]].keys():
            ab=abs(a[now[0]+1][now[1]]-b[now[0]+1][now[1]])
            lst[now[0]+1][now[1]][i+ab]=1
            lst[now[0]+1][now[1]][abs(i-ab)]=1

    # print(lst)
    if now[1]+1<w:
        if lst[now[0]][now[1]+1]==0:
            d.append((now[0],now[1]+1))
            lst[now[0]][now[1]+1]={}

        for i in lst[now[0]][now[1]].keys():
            ab=abs(a[now[0]][now[1]+1]-b[now[0]][now[1]+1])
            lst[now[0]][now[1]+1][i+ab]=1
            lst[now[0]][now[1]+1][abs(i-ab)]=1
    # print(d)
    # print(lst)
anslst=list(lst[-1][-1].keys())
anslst.sort(key=lambda x: abs(x))
print(abs(anslst[0]))

Submission status: Time Limit Exceeded

Solution code:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]


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

lst=[[0]*w for i in range(h)]

lst[0][0]={a[0][0]-b[0][0]:1,-a[0][0]+b[0][0]:1}
# print(lst)
d=deque([(0,0)])
while d:
    now=d.popleft()
    if now[0]+1<h:
        if lst[now[0]+1][now[1]]==0:
            d.append((now[0]+1,now[1]))
            lst[now[0]+1][now[1]]={}

        for i in lst[now[0]][now[1]].keys():
            ab=a[now[0]+1][now[1]]-b[now[0]+1][now[1]]
            lst[now[0]+1][now[1]][i+ab]=1
            lst[now[0]+1][now[1]][i-ab]=1

    # print(lst)
    if now[1]+1<w:
        if lst[now[0]][now[1]+1]==0:
            d.append((now[0],now[1]+1))
            lst[now[0]][now[1]+1]={}

        for i in lst[now[0]][now[1]].keys():
            ab=a[now[0]][now[1]+1]-b[now[0]][now[1]+1]
            lst[now[0]][now[1]+1][i+ab]=1
            lst[now[0]][now[1]+1][i-ab]=1
    # print(d)
    # print(lst)
anslst=list(lst[-1][-1].keys())
anslst.sort(key=lambda x: abs(x))
print(abs(anslst[0]))

Submission status: Time Limit Exceeded

Solution code:
def main():  
  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 = [[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 = [[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]))
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():  
  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]))
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    B_MAX = (80 + 80 - 1) * 80
    H, W = list(map(int, input().split(' ')))
    A = [list(map(int, input().split(' '))) for _ in range(H)]
    B = [list(map(int, input().split(' '))) for _ in range(H)]
    dp = [[[0 for _ in range(B_MAX + 1)] for _ in range(W)] for _ in range(H)]
    dp[0][0][abs(A[0][0] - B[0][0])] = 1
    max_b = abs(A[0][0] - B[0][0])
    for h in range(H):
        for w in range(W):
            if h == 0 and w == 0:
                continue
            d = abs(A[h][w] - B[h][w])
            max_b += d
            for b in range(min(B_MAX, max_b) + 1):
                v = 0
                if h > 0:
                    v = max(v, dp[h - 1][w][abs(b - d)])
                    if b + d <= B_MAX:
                        v = max(v, dp[h - 1][w][b + d])
                if w > 0:
                    v = max(v, dp[h][w - 1][abs(b - d)])
                    if b + d <= B_MAX:
                        v = max(v, dp[h][w - 1][b + d])
                dp[h][w][b] = v
    ans = 0
    while dp[H - 1][W - 1][ans] == 0:
        ans += 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    B_MAX = (80 + 80 - 1) * 80
    H, W = list(map(int, input().split(' ')))
    A = [list(map(int, input().split(' '))) for _ in range(H)]
    B = [list(map(int, input().split(' '))) for _ in range(H)]
    dp = [[[0 for _ in range(B_MAX + 1)] for _ in range(W)] for _ in range(H)]
    dp[0][0][abs(A[0][0] - B[0][0])] = 1
    for h in range(H):
        for w in range(W):
            if h == 0 and w == 0:
                continue
            d = abs(A[h][w] - B[h][w])
            for b in range(B_MAX + 1):
                v = 0
                if h > 0:
                    v = max(v, dp[h - 1][w][abs(b - d)])
                    if b + d <= B_MAX:
                        v = max(v, dp[h - 1][w][b + d])
                if w > 0:
                    v = max(v, dp[h][w - 1][abs(b - d)])
                    if b + d <= B_MAX:
                        v = max(v, dp[h][w - 1][b + d])
                dp[h][w][b] = v
    ans = 0
    while dp[H - 1][W - 1][ans] == 0:
        ans += 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import copy
stdin = sys.stdin


def ni(): return int(ns())


def na(): return list(map(int, stdin.readline().split()))


def naa(N): return [na() for _ in range(N)]


def ns(): return stdin.readline().rstrip()  # ignore trailing spaces


H, W = na()
A_array = naa(H)
B_array = naa(H)
C_array = [[abs(aa-bb) for aa, bb in zip(a, b)]
           for a, b in zip(A_array, B_array)]
# print(C_array)

ans_array = [set() for _ in range(W)]

ans_array[0].add(0)

for i in range(H):
    for j in range(W):
        for s in copy.deepcopy(ans_array[j]):
            ans_array[j].remove(s)
            ans_array[j].add(abs(s + C_array[i][j]))
            ans_array[j].add(abs(s - C_array[i][j]))
        # print(ans_array[j])
        if j != 0:
            for s in ans_array[j-1]:
                ans_array[j].add(abs(s + C_array[i][j]))
                ans_array[j].add(abs(s - C_array[i][j]))
#     print(ans_array)
# print(ans_array)

ans = 10 ** 9
for s in ans_array[W-1]:
    if abs(s) < ans:
        ans = abs(s)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

stdin = sys.stdin


def ni(): return int(ns())


def na(): return list(map(int, stdin.readline().split()))


def naa(N): return [na() for _ in range(N)]


def ns(): return stdin.readline().rstrip()  # ignore trailing spaces


H, W = na()
A_array = naa(H)
B_array = naa(H)
C_array = [[abs(aa-bb) for aa, bb in zip(a, b)]
           for a, b in zip(A_array, B_array)]
# print(C_array)

ans_array = [[set() for _ in range(W)] for _ in range(H)]

ans_array[0][0].add(C_array[0][0])

for i in range(H):
    for j in range(W):
        if i != 0:
            for s in ans_array[i-1][j]:
                ans_array[i][j].add(abs(s + C_array[i][j]))
                ans_array[i][j].add(abs(s - C_array[i][j]))
        if j != 0:
            for s in ans_array[i][j-1]:
                ans_array[i][j].add(abs(s + C_array[i][j]))
                ans_array[i][j].add(abs(s - C_array[i][j]))

# print(ans_array)

ans = 10 ** 9
for s in ans_array[H-1][W-1]:
    if abs(s) < ans:
        ans = abs(s)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

stdin = sys.stdin


def ni(): return int(ns())


def na(): return list(map(int, stdin.readline().split()))


def naa(N): return [na() for _ in range(N)]


def ns(): return stdin.readline().rstrip()  # ignore trailing spaces


H, W = na()
A_array = naa(H)
B_array = naa(H)
C_array = [[abs(aa-bb) for aa, bb in zip(a, b)]
           for a, b in zip(A_array, B_array)]
# print(C_array)

ans_array = [[set() for _ in range(W)] for _ in range(H)]

ans_array[0][0].add(C_array[0][0])

for i in range(H):
    for j in range(W):
        if i != 0:
            for s in ans_array[i-1][j]:
                ans_array[i][j].add(s + C_array[i][j])
                ans_array[i][j].add(s - C_array[i][j])
        if j != 0:
            for s in ans_array[i][j-1]:
                ans_array[i][j].add(s + C_array[i][j])
                ans_array[i][j].add(s - C_array[i][j])

# print(ans_array)

ans = 10 ** 9
for s in ans_array[H-1][W-1]:
    if abs(s) < ans:
        ans = abs(s)
print(ans)

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)]
num=0
for i in range(H):
  for j in range(W):
    num=max(num,abs(A[i][j]-B[i][j]))
num*=H+W
num+=1
    
#dp[i][j]=マス(i,j)における可能なポイントのリスト
dp=[[[False]*(num) for _ in range(W)] for _ in range(H)]
dp[0][0][0]=True

for i in range(W+H-1):
  I,J=0,0
  if i < H:
    I=i
    J=0
  else:
    I=H-1
    J=i-H+1
  while I>=0 and J<W:
    sa = abs(A[I][J] - B[I][J])
    for n in range(num):
      if not dp[I][J][n]:
        continue
      if I!=H-1:
        dp[I+1][J][n+sa]=True
        dp[I+1][J][abs(n-sa)]=True
      if J!=W-1:
        dp[I][J+1][n+sa]=True
        dp[I][J+1][abs(n-sa)]=True
    I-=1
    J+=1

sa = abs(A[H-1][W-1] - B[H-1][W-1])
ans=float("inf")
for n in range(num):
  if not dp[-1][-1][n]:
    continue
  ans = min(ans,abs(n-sa),n+sa)
print(ans)

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)]
num=(H+W)*80+1
#dp[i][j]=マス(i,j)における可能なポイントのリスト
dp=[[[False]*(num) for _ in range(W)] for _ in range(H)]
dp[0][0][0]=True

for i in range(W+H-1):
  I,J=0,0
  if i < H:
    I=i
    J=0
  else:
    I=H-1
    J=i-H+1
  while I>=0 and J<W:
    sa = abs(A[I][J] - B[I][J])
    for n in range(num):
      if not dp[I][J][n]:
        continue
      if I!=H-1:
        dp[I+1][J][n+sa]=True
        dp[I+1][J][abs(n-sa)]=True
      if J!=W-1:
        dp[I][J+1][n+sa]=True
        dp[I][J+1][abs(n-sa)]=True
    I-=1
    J+=1

sa = abs(A[H-1][W-1] - B[H-1][W-1])
ans=float("inf")
for n in range(num):
  if not dp[-1][-1][n]:
    continue
  ans = min(ans,abs(n-sa),n+sa)
print(ans)

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

#dp[i][j]=マス(i,j)における可能なポイントのリスト
dp=[[set() for _ in range(W)] for _ in range(H)]
dp[0][0].add(0)

for i in range(W+H-1):
  I,J=0,0
  if i < H:
    I=i
    J=0
  else:
    I=H-1
    J=i-H+1
  while I>=0 and J<W:
    sa = A[I][J] - B[I][J]
    for point in dp[I][J]:
      if I!=H-1:
        dp[I+1][J].add(point+sa)
        dp[I+1][J].add(abs(point-sa))
      if J!=W-1:
        dp[I][J+1].add(point+sa)
        dp[I][J+1].add(abs(point-sa))
    I-=1
    J+=1

ans=dp[H-1][W-1]
sa = A[H-1][W-1] - B[H-1][W-1]
res=float("inf")
for p in ans:
  res=min(res,abs(p+sa),abs(p-sa))
print(res)

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

#dp[i][j]=マス(i,j)における可能なポイントのリスト
dp=[[set() for _ in range(W)] for _ in range(H)]
dp[0][0].add(0)

for i in range(W+H-1):
  I,J=0,0
  if i < H:
    I=i
    J=0
  else:
    I=H-1
    J=i-H+1
  while I>=0 and J<W:
    sa = A[I][J] - B[I][J]
    for point in dp[I][J]:
      if I!=H-1:
        dp[I+1][J].add(point+sa)
        dp[I+1][J].add(point-sa)
      if J!=W-1:
        dp[I][J+1].add(point+sa)
        dp[I][J+1].add(point-sa)
    I-=1
    J+=1

ans=dp[H-1][W-1]
sa = A[H-1][W-1] - B[H-1][W-1]
res=float("inf")
for p in ans:
  res=min(res,abs(p+sa),abs(p-sa))
print(res)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
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)]

#dp[i][j]=マス(i,j)における可能なポイントのリスト
dp=[[set() for _ in range(W)] for _ in range(H)]
dp[0][0].add(0)

for i in range(W+H-1):
  I,J=0,0
  if i < H:
    I=i
    J=0
  else:
    I=H-1
    J=i-H+1
  while I>=0 and J<W:
    sa = A[I][J] - B[I][J]
    for point in dp[I][J]:
      if I!=H-1:
        dp[I+1][J].add(point+sa)
        dp[I+1][J].add(point-sa)
      if J!=W-1:
        dp[I][J+1].add(point+sa)
        dp[I][J+1].add(point-sa)
    I-=1
    J+=1

ans=dp[H-1][W-1]
sa = A[H-1][W-1] - B[H-1][W-1]
res=float("inf")
for p in ans:
  res=min(res,abs(p+sa),abs(p-sa))
print(res)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
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)]

#dp[i][j]=マス(i,j)における可能なポイントのリスト
dp=[[[] for _ in range(W)] for _ in range(H)]
dp[0][0].append(0)

for i in range(W+H-1):
  I,J=0,0
  if i < H:
    I=i
    J=0
  else:
    I=H-1
    J=i-H+1
  while I>=0 and J<W:
    sa = A[I][J] - B[I][J]
    for point in dp[I][J]:
      if I!=H-1:
        dp[I+1][J].append(point+sa)
        dp[I+1][J].append(point-sa)
      if J!=W-1:
        dp[I][J+1].append(point+sa)
        dp[I][J+1].append(point-sa)
    I-=1
    J+=1

ans=dp[H-1][W-1]
sa = A[H-1][W-1] - B[H-1][W-1]
res=float("inf")
for p in ans:
  res=min(res,abs(p+sa),abs(p-sa))
print(res)