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
import  math
import fractions
from collections import defaultdict
stdin = sys.stdin
        
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))
    
INF=10**18
    
H,W=nm()
A=[]
B=[]
for i in range(H):
    A.append(nl())
    
for i in range(H):
    B.append(nl())
    
    
dp=[[[False]*180*(H+W) for _ in range(W)] for i in range(H)]#yoko tate sa
    
dp[0][0][abs(A[0][0]-B[0][0])]=True
for i in range(1,W):
    tmp=abs(A[0][i]-B[0][i])
    for k in range(81*(H+W)-tmp):
        if(dp[0][i-1][k-tmp] or dp[0][i-1][k+tmp] or dp[0][i-1][tmp-k]):
            dp[0][i][k]=True
    
for i in range(1,H):
    for k in range(W):
        tmp=abs(A[i][k]-B[i][k])
        if(k==0):
            for j in range(81*(H+W)-tmp):
                if(dp[i-1][k][j-tmp] or dp[i-1][k][j+tmp] or dp[i-1][k][tmp-j]):
                    dp[i][k][j]=True
        else:
            for j in range(81*(H+W)-tmp):
                if(dp[i-1][k][j-tmp] or dp[i-1][k][j+tmp] or dp[i-1][k][tmp-j] or dp[i][k-1][j-tmp] or dp[i][k-1][j+tmp] or dp[i][k-1][tmp-j]):
                    dp[i][k][j]=True
    
ans_l=dp[H-1][W-1]
for i in range(162*(H+W)):
    if(ans_l[i]):
        print(i)
        sys.exit(0)

Submission status: Time Limit Exceeded

Solution code:
import sys
import  math
import fractions
from collections import defaultdict
stdin = sys.stdin
        
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))
    
INF=10**18
    
H,W=nm()
A=[]
B=[]
for i in range(H):
    A.append(nl())
    
for i in range(H):
    B.append(nl())
    
    
dp=[[[False]*180*(H+W) for _ in range(W)] for i in range(H)]#yoko tate sa
    
dp[0][0][abs(A[0][0]-B[0][0])]=True
for i in range(1,W):
    tmp=abs(A[0][i]-B[0][i])
    for k in range(162*(H+W)-tmp):
        if(dp[0][i-1][k-tmp] or dp[0][i-1][k+tmp] or dp[0][i-1][tmp-k]):
            dp[0][i][k]=True
    
for i in range(1,H):
    for k in range(W):
        tmp=abs(A[i][k]-B[i][k])
        if(k==0):
            for j in range(162*(H+W)-tmp):
                if(dp[i-1][k][j-tmp] or dp[i-1][k][j+tmp] or dp[i-1][k][tmp-j]):
                    dp[i][k][j]=True
        else:
            for j in range(162*(H+W)-tmp):
                if(dp[i-1][k][j-tmp] or dp[i-1][k][j+tmp] or dp[i-1][k][tmp-j] or dp[i][k-1][j-tmp] or dp[i][k-1][j+tmp] or dp[i][k-1][tmp-j]):
                    dp[i][k][j]=True
    
ans_l=dp[H-1][W-1]
for i in range(162*(H+W)):
    if(ans_l[i]):
        print(i)
        sys.exit(0)

Submission status: Time Limit Exceeded

Solution code:
import sys
import  math
import fractions
from collections import defaultdict
stdin = sys.stdin
     
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

INF=10**18

H,W=nm()
A=[]
B=[]
for i in range(H):
    A.append(nl())

for i in range(H):
    B.append(nl())


dp=[[[] for _ in range(W)] for i in range(H)]#yoko tate sa

dp[0][0].append(A[0][0]-B[0][0])
dp[0][0].append(B[0][0]-A[0][0])
for i in range(1,H):
    for k in range(len(dp[0][i-1])):
        dp[0][i].append(dp[0][i-1][k]+A[0][i]-B[0][i])
        dp[0][i].append(dp[0][i-1][k]+B[0][i]-A[0][i])

for i in range(H):
    for k in range(W):
        if(k==0):
           for j in range(len(dp[i-1][k])):
                dp[i][k].append(dp[i-1][k][j]+A[i][k]-B[i][k]) 
                dp[i][k].append(dp[i-1][k][j]+B[i][k]-A[i][k])
        else:
            for j in range(len(dp[i-1][k])):
                dp[i][k].append(dp[i-1][k][j]+A[i][k]-B[i][k]) 
                dp[i][k].append(dp[i-1][k][j]+B[i][k]-A[i][k]) 
            for j in range(len(dp[i][k-1])):
                dp[i][k].append(dp[i][k-1][j]+A[i][k]-B[i][k]) 
                dp[i][k].append(dp[i][k-1][j]+B[i][k]-A[i][k])


ans_l=dp[H-1][W-1]
ans_l=list(map(lambda x:abs(x),ans_l))
ans_l.sort()

print(ans_l[0])

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
A = [ [None]*W for _ in range(H) ]
B = [ [None]*W for _ in range(H) ]
for h in range(H):
  for i,a in enumerate(list(map(int,input().split()))):
    A[h][i] = a

for h in range(H):
  for i,b in enumerate(list(map(int,input().split()))):
    B[h][i] = b

dp = [ [ [False]*(81*(H+W)) for _ in range(W+1) ] for _ in range(H+1) ]
dp[0][0][abs(A[0][0]-B[0][0])] = True

for h in range(H):
  for w in range(W):
    for k in range(80*(H+W)):
      if dp[h][w][k]:
        if h+1 < H:
          # (a,b) = (red,blue)
          dp[h+1][w][abs(k-(abs(A[h+1][w]-B[h+1][w])))] = True
          dp[h+1][w][abs(k+(abs(A[h+1][w]-B[h+1][w])))] = True

        if w+1 < W:
          # (a,b) = (red,blue)
          dp[h][w+1][abs(k-(abs(A[h][w+1]-B[h][w+1])))] = True
          dp[h][w+1][abs(k+(abs(A[h][w+1]-B[h][w+1])))] = True

for i in range(81*H*W+1):
  if dp[H-1][W-1][i]: 
    print(i)
    exit()

Submission status: Time Limit Exceeded

Solution code:

from collections import deque
R,B = 1,0
INF = 10**15
H,W = map(int,input().split())
A = [ [None]*W for _ in range(H) ]
B = [ [None]*W for _ in range(H) ]
for h in range(H):
  for i,a in enumerate(list(map(int,input().split()))):
    A[h][i] = a

for h in range(H):
  for i,b in enumerate(list(map(int,input().split()))):
    B[h][i] = b

# (r,c,red,blue)
q = deque([(0,0,A[0][0],B[0][0]), (0,0,B[0][0],A[0][0])])
move = [(1,0), (0,1)]
res = INF
while q:
  r,c,red,blue = q.popleft()
  if r==H-1 and c==W-1:
    res = min(res, abs(red-blue))
    continue

  for y,x in move:
    if r+y >= H or c+x >= W: continue
    #(A,B) = (red,blue)
    nr,nc = r+y, c+x
    q.append((nr,nc,red+A[nr][nc],blue+B[nr][nc]))
    q.append((nr,nc,red+B[nr][nc],blue+A[nr][nc]))

print(res)

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 _ in range(h)]
b = [list(map(int, input().split())) for _ in range(h)]
m = (h + w - 1) * 80 + 1
dp = [[[False] * m for _ in range(w)] for _ in range(h)]
dp[0][0][abs(b[0][0] - a[0][0])] = True
for i in range(h):
    for j in range(w):
        x = abs(b[i][j] - a[i][j])
        for k in range(m):
            if i > 0:
                if 0 <= abs(x + k) < m:
                    dp[i][j][abs(x + k)] |= dp[i-1][j][k]
                if 0 <= abs(x - k) < m:
                    dp[i][j][abs(x - k)] |= dp[i-1][j][k]
            if j > 0:
                if 0 <= abs(x + k) < m:
                    dp[i][j][abs(x + k)] |= dp[i][j-1][k]
                if 0 <= abs(x - k) < m:
                    dp[i][j][abs(x - k)] |= dp[i][j-1][k]

for i in range(m):
    if dp[h-1][w-1][i]:
        print(i)
        exit()

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 _ in range(h)]
b = [list(map(int, input().split())) for _ in range(h)]

dp = [[set() for _ in range(w)] for _ in range(h)]
dp[0][0].add(abs(b[0][0] - a[0][0]))
for i in range(h):
    for j in range(w):
        t = abs(b[i][j] - a[i][j])
        if i > 0:
            for x in dp[i-1][j]:
                dp[i][j].add(abs(x + t))
                dp[i][j].add(abs(x - t))
        if j > 0:
            for x in dp[i][j-1]:
                dp[i][j].add(abs(x + t))
                dp[i][j].add(abs(x - t))

#print(dp)
ans = sorted(list(dp[h-1][w-1]))
print(ans[0])

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict
readline = sys.stdin.buffer.readline
# sys.setrecursionlimit(10**5)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


def main():
    H, W = geta(int)
    u = []
    for _ in range(H):
        u.append(list(geta(int)))

    for i in range(H):
        b = tuple(geta(int))
        for j, bj in enumerate(b):
            u[i][j] = abs(u[i][j] - bj)

    u_max = 160 * H * W

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

    dp[0][0].add(u[0][0])

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

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict
readline = sys.stdin.buffer.readline
# sys.setrecursionlimit(10**5)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


def main():
    H, W = geta(int)
    u = []
    for _ in range(H):
        u.append(list(geta(int)))

    for i in range(H):
        b = tuple(geta(int))
        for j, bj in enumerate(b):
            u[i][j] = abs(u[i][j] - bj)

    u_max = 160 * H * W

    dp = [[[False] * (u_max + 1) for _ in range(W)] for _ in range(H)]

    dp[0][0][u[0][0]] = True
    for i in range(H):
        for j in range(W):
            for k in range(u_max + 1):
                if dp[i][j][k]:
                    if i != H - 1:
                        dp[i + 1][j][k + u[i + 1][j]] = True
                        dp[i + 1][j][abs(k - u[i + 1][j])] = True
                    if j != W - 1:
                        dp[i][j + 1][k + u[i][j + 1]] = True
                        dp[i][j + 1][abs(k - u[i][j + 1])] = True

    for k, t in enumerate(dp[H - 1][W - 1]):
        if t:
            print(k)
            break


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
H,W=map(int,input().split())
A=[list(map(int,input().split())) for i in range(H)]
for i in range(H):
    B=list(map(int,input().split()))
    for j in range(W):
        A[i][j]=abs(A[i][j]-B[j])
dp=[[set() for i in range(W)] for i in range(H)]
dp[0][0].add(A[0][0])
for i in range(H):
    for j in range(W):
        for nx,ny in [(i+1,j),(i,j+1)]:
            if nx>=H or ny>=W:
                continue
            for k in dp[i][j]:
                p=k+A[nx][ny]
                m=abs(k-A[nx][ny])
                dp[nx][ny].add(p)
                dp[nx][ny].add(m)
ans=10**18
for k in dp[H-1][W-1]:
    ans=min(ans,k)
print(ans)

Submission status: Time Limit Exceeded

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

dp=[[[False]*(80*H*W-1) for i in range(W)] for i in range(H)]
dp[0][0][A[0][0]]=True
for i in range(H):
    for j in range(W):
        for x,y in [(0,1),(1,0)]:
            nx,ny=i+x,j+y
            if nx>=H or ny>=W:
                continue
            for x in range(81):
                if dp[i][j][x]:
                    if x+A[nx][ny]<=80:
                        dp[nx][ny][x+A[nx][ny]]=True
                        dp[nx][ny][abs(x-A[nx][ny])]=True
for x in range(81):
    if dp[i][j][x]:
        print(x)
        exit()

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 = []
  for i in range(h):
    s = list(map(int,readline().split()))
    a.append(s)
  b = []
  for i in range(h):
    t = list(map(int,readline().split()))
    b.append(t)
  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 = [[[0]*6321 for i in range(w)] for _ in range(h)]
  dp[0][0][C[0][0]] = 1

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

  for i in range(6321):
    if dp[h-1][w-1][i]:
      print(i)
      break
      
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    H, W = map(int, input().split())
    A = []
    for _ in range(H):
        A += map(int, input().split())  # 速度のため一次元で管理
    B = []
    for _ in range(H):
        B += map(int, input().split())  # 速度のため一次元で管理

    dp = [0] * (H * W)  # 速度のため一次元で管理,dp[pos]:=bit,[-80*H*W,80*H*W]->[0,2*80*H*W]
    d = abs(A[0] - B[0])
    dp[0] |= 1 << (80 * H * W + d)
    dp[0] |= 1 << (80 * H * W - d)

    for r in range(H):
        for c in range(W):
            p = r * W + c
            d = abs(A[p] - B[p])
            if r > 0:
                dp[p] |= (dp[p - W] << d)
                dp[p] |= (dp[p - W] >> d)
            if c > 0:
                dp[p] |= (dp[p - 1] << d)
                dp[p] |= (dp[p - 1] >> d)

    ans = 2 * 80 * H * W + 1
    for j in range(2 * 80 * H * W + 1):
        if (dp[H * W - 1] >> j) & 1:
            t = j - 80 * H * W
            if ans > abs(t):
                ans = abs(t)
    print(ans)


if __name__ == '__main__':
    main()

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 = []
for i in range(h):
  s = list(map(int,readline().split()))
  a.append(s)
b = []
for i in range(h):
  t = list(map(int,readline().split()))
  b.append(t)

dp = [[set() for _ in range(w)] for _ in range(h)]
dp[0][0].add(abs(a[0][0]-b[0][0]))

for i in range(h):
  for j in range(w):
    for k in dp[i][j]:
        if i < h-1:
          c = abs(a[i+1][j]-b[i+1][j])
          if k+c < 5000:
            dp[i+1][j].add(k+c)
          dp[i+1][j].add(abs(k-c))
        if j < w-1:
          d = abs(a[i][j+1]-b[i][j+1])
          if k+d < 5000:
            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:
h,w = map(int,input().split())
a = []
for i in range(h):
  s = list(map(int,input().split()))
  a.append(s)
b = []
for i in range(h):
  t = list(map(int,input().split()))
  b.append(t)

dp = [[set() for _ in range(w)] for _ in range(h)]
dp[0][0].add(abs(a[0][0]-b[0][0]))

for i in range(h):
  for j in range(w):
    for k in dp[i][j]:
        if i < h-1:
          c = abs(a[i+1][j]-b[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 = abs(a[i][j+1]-b[i][j+1])
          if k+d < 6321:
            dp[i][j+1].add(k+d)
          dp[i][j+1].add(abs(k-d))
      
ans = list(dp[h-1][w-1])
print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
h,w = map(int,input().split())
a = []
for i in range(h):
  s = list(map(int,input().split()))
  a.append(s)
b = []
for i in range(h):
  t = list(map(int,input().split()))
  b.append(t)

dp = [[[False]*6321 for i in range(w)] for _ 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(6321):
      if dp[i][j][k]:
        if i < h-1:
          c = abs(a[i+1][j]-b[i+1][j])
          if k+c < 6321:
            dp[i+1][j][k+c] = True
          dp[i+1][j][abs(k-c)] = True
        if j < w-1:
          d = abs(a[i][j+1]-b[i][j+1])
          if k+d < 6321:
            dp[i][j+1][k+d] = True
          dp[i][j+1][abs(k-d)] = True
          
for i in range(6321):
  if dp[h-1][w-1][i]:
    print(i)
    break

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 _ in range(H)]
B = [list(map(int, input().split())) for _ in range(H)]
can_make = [[None for _ in range(W)] for _ in range(H)]
for i in range(H):
    for j in range(W):
        x = A[i][j] - B[i][j]
        if i == j == 0:
            can_make[i][j] = set([abs(x)])
            continue
        st = set()
        if i > 0:
            for y in can_make[i-1][j]:
                if abs(y + x) <= 6400:
                    st.add(abs(y + x))
                st.add(abs(y - x))
        if j > 0:
            for y in can_make[i][j-1]:
                if abs(y + x) <= 6400:
                    st.add(abs(y + x))
                st.add(abs(y - x))
        can_make[i][j] = st
print(min(can_make[-1][-1], key=lambda x: abs(x)))

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 _ in range(H)]
B = [list(map(int, input().split())) for _ in range(H)]
can_make = [[None for _ in range(W)] for _ in range(H)]
for i in range(H):
    for j in range(W):
        x = A[i][j] - B[i][j]
        if i == j == 0:
            can_make[i][j] = set([abs(x)])
            continue
        st = set()
        if i > 0:
            for y in can_make[i-1][j]:
                st.add(abs(y + x))
                st.add(abs(y - x))
        if j > 0:
            for y in can_make[i][j-1]:
                st.add(abs(y + x))
                st.add(abs(y - x))
        can_make[i][j] = st
print(min(can_make[-1][-1], key=lambda x: abs(x)))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)

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

U = (H + W) * 80
Um = U // 2

dp = [[[0] * (U + 1) for _ in range(W)] for _ in range(H)]
d = abs(A[0][0] - B[0][0])
dp[0][0][Um + d] = 1
dp[0][0][Um - d] = 1


for i in range(H):
    for j in range(W):
        if i < H - 1:
            d = abs(A[i + 1][j] - B[i + 1][j])
            for k in range(U - d + 1):
                dp[i + 1][j][k + d] |= dp[i][j][k]
            for k in range(d, U + 1):
                dp[i + 1][j][k - d] |= dp[i][j][k]
        if j < W - 1:
            d = abs(A[i][j + 1] - B[i][j + 1])
            for k in range(U - d + 1):
                dp[i][j + 1][k + d] |= dp[i][j][k]
            for k in range(d, U + 1):
                dp[i][j + 1][k - d] |= dp[i][j][k]

ans = 10 ** 18
for i, p in enumerate(dp[H - 1][W - 1]):
    if p:
        ans = min(ans, abs(Um - i))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)

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

U = 80 * 80 + 10
Um = U // 2

dp = [[[0] * (U + 1) for _ in range(W)] for _ in range(H)]
d = abs(A[0][0] - B[0][0])
dp[0][0][Um + d] = 1
dp[0][0][Um - d] = 1


for i in range(H):
    for j in range(W):
        if i < H - 1:
            d = abs(A[i + 1][j] - B[i + 1][j])
            for k in range(U - d + 1):
                dp[i + 1][j][k + d] |= dp[i][j][k]
            for k in range(d, U + 1):
                dp[i + 1][j][k - d] |= dp[i][j][k]
        if j < W - 1:
            d = abs(A[i][j + 1] - B[i][j + 1])
            for k in range(U - d + 1):
                dp[i][j + 1][k + d] |= dp[i][j][k]
            for k in range(d, U + 1):
                dp[i][j + 1][k - d] |= dp[i][j][k]

ans = 10 ** 18
for i, p in enumerate(dp[H - 1][W - 1]):
    if p:
        ans = min(ans, abs(Um - i))
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)]

Z = sum(sum(a) for a in A) + sum(sum(b) for b in B) + 10

dp = [[0] * (W + 1) for _ in range(H + 1)]
dp[0][0] = (1 << Z)

for h in range(H):
    for w in range(W):
        d = dp[h][w]
        k = abs(A[h][w] - B[h][w])

        dp[h + 1][w] |= (d << k) | (d >> k)
        dp[h][w + 1] |= (d << k) | (d >> k)

ans = 10**18
for a in (dp[H][W - 1], dp[H - 1][W]):
    for d in range(Z * 2 + 10):
        if a & (1 << d) != 0:
            ans = min(ans, abs(d - Z))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    import random
    n=random.randint(4,16)
    a=sorted([random.randint(0,5) for _ in range(n)])[::-1]
    return n,a

show_flg=False
show_flg=True

h,w=LI()
ans=0
a=[[0]*(1+w)]
b=[[0]*(1+w)]
for i in range(h):
    a.append([0]+LI())
for i in range(h):
    b.append([0]+LI())

dp=[[set() for i in range(w+1)]for j in range(h+1)]

dp[0][1].add(0)

for i in range(1,h+1):
    for j in range(1,w+1):
        d=a[i][j]-b[i][j]
        M=80*(161-i-j)
        m=-80*(161-i-j)

        for x in dp[i-1][j]:
            if m<=x+d<=M:dp[i][j].add(x+d)
            if m<=x-d<=M:dp[i][j].add(x-d)

        for x in dp[i][j-1]:
            if m<=x+d<=M:dp[i][j].add(x+d)
            if m<=x-d<=M:dp[i][j].add(x-d)

ans=min([abs(i) for i in dp[h][w]])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    h,w=map(int,input().split())
    a=[list(map(int,input().split())) for _ in [0]*h]
    b=[list(map(int,input().split())) for _ in [0]*h]
    c=[[abs(a[i][j]-b[i][j]) for j in range(w)] for i in range(h)]
    t=4000
    dp1=[[False]*(t+1) for _ in [0]*w]
    dp1[0][c[0][0]]=True
    for j in range(1,w):
        v=c[0][j]
        for k in range(t+1):
            if dp1[j-1][k]==True:
                if v+k<=t:
                    dp1[j][v+k]=True
                if abs(v-k)<=0:
                    dp1[j][abs(v-k)]=True
    for i in range(1,h):
        dp2=[[False]*(t+1) for _ in [0]*w]
        for j in range(w):
            v=c[i][j]
            for k in range(t+1):
                if dp1[j][k]==True:
                    if v+k<=t:
                        dp2[j][v+k]=True
                    if abs(v-k)<=t:
                        dp2[j][abs(v-k)]=True
        for j in range(1,w):
            v=c[i][j]
            for k in range(t+1):
                if dp2[j-1][k]==True:
                    if v+k<=t:
                        dp2[j][v+k]=True
                    if abs(v-k)<=t:
                        dp2[j][abs(v-k)]=True  
        dp1=dp2
    for i,j in enumerate(dp1[w-1]):
        if j==True:
            print(i)
            break
main()

Submission status: Time Limit Exceeded

Solution code:
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)]

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

Submission status: Time Limit Exceeded

Solution code:
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)]
kanousei = [[[] for i in range(w)] for j in range(h)]
  # print(kanousei)
kanousei[0][0].append(abs(a[0][0]-b[0][0]))
kanousei[0][0].append(abs(b[0][0]-a[0][0]))
kanousei[0][0] = set(kanousei[0][0])
for RangeFromZero in range(1,h+w-1):
    for x in range(RangeFromZero,-1,-1):
        y = RangeFromZero-x
        if x < w and y < h:
            if x and len(kanousei[y][x-1]):
                for num in kanousei[y][x-1]:
                    kanousei[y][x].append(num+abs(a[y][x]-b[y][x]))
                    kanousei[y][x].append(abs(num-abs(a[y][x]-b[y][x])))
            if y and len(kanousei[y-1][x]):
                for num in kanousei[y-1][x]:
                    kanousei[y][x].append(num+abs(a[y][x]-b[y][x]))
                    kanousei[y][x].append(abs(num-abs(a[y][x]-b[y][x])))
            kanousei[y][x] = set(kanousei[y][x])
  #     print(kanousei)
print(min(kanousei[h-1][w-1]))

Submission status: Time Limit Exceeded

Solution code:
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)]
kanousei = [[[] for i in range(w)] for j in range(h)]
  # print(kanousei)
kanousei[0][0].append(abs(a[0][0]-b[0][0]))
kanousei[0][0].append(abs(b[0][0]-a[0][0]))
for RangeFromZero in range(1,h+w-1):
    for x in range(RangeFromZero,-1,-1):
        y = RangeFromZero-x
        if x < w and y < h:
            if x and len(kanousei[y][x-1]):
                for num in kanousei[y][x-1]:
                    kanousei[y][x].append(num+abs(a[y][x]-b[y][x]))
                    kanousei[y][x].append(abs(num-abs(a[y][x]-b[y][x])))
            if y and len(kanousei[y-1][x]):
                for num in kanousei[y-1][x]:
                    kanousei[y][x].append(num+abs(a[y][x]-b[y][x]))
                    kanousei[y][x].append(abs(num-abs(a[y][x]-b[y][x])))
            kanousei[y][x] = set(kanousei[y][x])
print(min(kanousei[h-1][w-1]))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
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)]
kanousei = np.array([[[0] * 6401] * w] * h)
kanousei[0][0][abs(a[0][0]-b[0][0])] = 1
kanousei[0][0][abs(b[0][0]-a[0][0])] = 1
for RangeFromZero in range(1,h+w-1):
  #     print(RangeFromZero)
    for x in range(RangeFromZero,-1,-1):
        y = RangeFromZero-x
  #         print(x,y)
        if x < w and y < h:
            if 0 < x:
                for i in range(6401):
                    if kanousei[y][x-1][i] == 1:
                        kanousei[y][x][i+abs(a[y][x]-b[y][x])] = 1
                        kanousei[y][x][abs(i-abs(a[y][x]-b[y][x]))] = 1
            if 0 < y:
                for i in range(6401):
                    if kanousei[y-1][x][i] == 1:
                        kanousei[y][x][i+abs(a[y][x]-b[y][x])] = 1
                        kanousei[y][x][abs(i-abs(a[y][x]-b[y][x]))] = 1
for i in range(6401):
    if kanousei[h-1][w-1][i] == 1:
        print(i)
        exit()

Submission status: Time Limit Exceeded

Solution code:
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)]
kanousei = [[[0] * 6401 for i in range(w)] for j in range(h)]
kanousei[0][0][abs(a[0][0]-b[0][0])] = 1
kanousei[0][0][abs(b[0][0]-a[0][0])] = 1
for RangeFromZero in range(1,h+w-1):
  #     print(RangeFromZero)
    for x in range(RangeFromZero,-1,-1):
        y = RangeFromZero-x
  #         print(x,y)
        if x < w and y < h:
            if 0 < x:
                for i in range(6401):
                    if kanousei[y][x-1][i] == 1:
                        kanousei[y][x][i+abs(a[y][x]-b[y][x])] = 1
                        kanousei[y][x][abs(i-abs(a[y][x]-b[y][x]))] = 1
            if 0 < y:
                for i in range(6401):
                    if kanousei[y-1][x][i] == 1:
                        kanousei[y][x][i+abs(a[y][x]-b[y][x])] = 1
                        kanousei[y][x][abs(i-abs(a[y][x]-b[y][x]))] = 1
    for i in range(6401):
        if kanousei[h-1][w-1][i] == 1:
            print(i)
            exit()