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

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**5)

H, W = map(int, input().split())
A = [[int(i) for i in input().split()] for _ in range(H)]
B = [[int(i) for i in input().split()] for _ in range(H)]
C = [[abs(A[y][x] - B[y][x]) for x in range(W)] for y in range(H)]

N = 13000
half = N // 2

dp = [[0] * W for _ in range(H)]
dp[0][0] = (1 << (half - C[0][0])) | (1 << (half + C[0][0]))

for y in range(H) :
    for x in range(W) :
        if y != 0 :
            dp[y][x] |= (dp[y-1][x] >> C[y][x]) | (dp[y-1][x] << C[y][x])
                    
        if x != 0 :
            dp[y][x] |= (dp[y][x-1] >> C[y][x]) | (dp[y][x-1] << C[y][x])

b = bin(dp[-1][-1])[2:][::-1]
ret = float('inf')
for k, v in enumerate(b) :
    if v == '1' :
        ret = min(ret, abs(k - half))
        
print(ret)

Solution (Python):


import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

def build_grid(H, W, intv, _type, space=True, padding=False):
    
    if space:
        _input = lambda: input().split()
    else:
        _input = lambda: input()
    _list = lambda: list(map(_type, _input()))
    
    if padding:
        offset = 1
    else:
        offset = 0
    grid = list2d(H+offset*2, W+offset*2, intv)
    for i in range(offset, H+offset):
        row = _list()
        for j in range(offset, W+offset):
            grid[i][j] = row[j-offset]
    return grid

H, W = MAP()
MAXV = 160 * 80

grid1 =build_grid(H, W, 0, int)
grid2 =build_grid(H, W, 0, int)
grid = list2d(H+1, W+1, 0)
for i in range(H):
    for j in range(W):
        grid[i+1][j+1] = abs(grid1[i][j]-grid2[i][j])

dp = list2d(H+1, W+1, 0)

dp[1][1] = (1<<MAXV-grid[1][1]) | (1<<MAXV+grid[1][1])
for i in range(1, H+1):
    for j in range(1, W+1):
        v = grid[i][j]
        dp[i][j] |= dp[i-1][j] << v
        dp[i][j] |= dp[i-1][j] >> v
        dp[i][j] |= dp[i][j-1] << v
        dp[i][j] |= dp[i][j-1] >> v
ans = INF
S = dp[H][W] >> MAXV
for k in range(MAXV+1):
    if S & (1<<k):
        ans = min(ans, k)
print(ans)

Solution (Python):
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 j in range(H)]
m=80*(H+W)
d[0][0]=1<<m
for h in range(H):
    for w in range(W):
        x=abs(A[h][w]-B[h][w])
        if h>0:
            d[h][w]|=d[h-1][w]
        if w>0:
            d[h][w]|=d[h][w-1]
        d[h][w]=d[h][w]<<x|d[h][w]>>x
x,y=1<<m,1<<m
for i in range(99):
    if d[H-1][W-1]&x or d[H-1][W-1]&y:
        print(i)
        exit()
    x<<=1
    y>>=1

Solution (Python):
MAX_DIFF = 80
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)]
c = [[abs(a[i][j]-b[i][j]) for j in range(w)] for i in range(h)]

mask = (1 << (h+w)*MAX_DIFF)-1
sets = [[0 for j in range(w)] for i in range(h)]
sets[0][0] = (1 << MAX_DIFF+c[0][0]) | (1 << MAX_DIFF-c[0][0])
for i in range(1, h):
    sets[i][0] |= (sets[i-1][0] << MAX_DIFF+c[i][0]
                   ) | (sets[i-1][0] << MAX_DIFF-c[i][0])
for i in range(1, w):
    sets[0][i] |= (sets[0][i-1] << MAX_DIFF+c[0][i]
                   ) | (sets[0][i-1] << MAX_DIFF-c[0][i])
for i in range(1, h):
    for j in range(1, w):
        sets[i][j] |= (sets[i-1][j] << MAX_DIFF+c[i][j]
                       ) | (sets[i-1][j] << MAX_DIFF-c[i][j])
        sets[i][j] |= (sets[i][j-1] << MAX_DIFF+c[i][j]
                       ) | (sets[i][j-1] << MAX_DIFF-c[i][j])


s = bin(sets[h-1][w-1]+(1 << (h+w)*MAX_DIFF))
min_diff = 1 << MAX_DIFF
for i in range(len(s)):
    if s[-1-i] == '1':
        min_diff = min(min_diff, abs(i-(h+w-1)*MAX_DIFF))
print(min_diff)

Solution (Python):
import sys

read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines







def main():
	h, w = map(int, input().split())
	
	G = [[0] * w for i in range(h)]
	A = [0]*h
	B = [0]*h
	
	for i in range(h):
		A[i] = list(map(int, input().split()))
	for i in range(h):
		B[i] = list(map(int, input().split()))
	
	for i in range(h):
		for j in range(w):
			G[i][j]=abs(A[i][j]-B[i][j])

	M = (h + w) * 80

	li = [[[0] * M for i in range(w)] for j in range(h)]
	
	li[0][0][G[0][0]] = 1
	for i in range(h):
		for j in range(w):
			for k in range(M):
				
				if li[i][j][k] == 1:
					if i < h - 1:
						li[i + 1][j][abs(k - G[i+1][j])] = 1
						li[i + 1][j][abs(k + G[i+1][j])] = 1
					if j < w - 1:
						li[i][j + 1][abs(k - G[i][j+1])] = 1
						li[i][j + 1][abs(k + G[i][j+1])] = 1

	for i in range(M):
		if li[h-1][w - 1][i] == 1:
			print(i)
			exit(0)


if __name__ == "__main__":
	main()

Solution (Python):
import sys
def input():
    return sys.stdin.readline()[:-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)]
d=[[0 for i in range(w)] for j in range(h)]
maxd=1
for i in range(h):
    for j in range(w):
        d[i][j] = abs(a[i][j]-b[i][j])
        maxd=max(maxd,d[i][j])
dp=[[0 for j in range(w)] for k in range(h)]
c=20000
dp[0][0] |= 1 << c+d[0][0]
for i in range(h):
    for j in range(w):
        if i+1<h:
            dp[i+1][j] |= dp[i][j] << d[i+1][j]
            dp[i+1][j] |= dp[i][j] >> d[i+1][j]
        if j+1<w:
            dp[i][j+1] |= dp[i][j] << d[i][j+1]
            dp[i][j+1] |= dp[i][j] >> d[i][j+1]
m=1000000
cnt = 0
for x in bin(dp[h-1][w-1])[2:][::-1]:
    if x=='1':
        m=min(m,abs(cnt-c))
    cnt+=1
print(m)

Solution (Python):
def main(sample_file = ''):

    """ convenient functions
    
    
    
    
    
    """

    """convenient decorator
    
    
        
        
        
        
        
        
        
        
        
        
    """
    
    
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product 
    
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  
        b, e = 2, 0  
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict 
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest 
    from copy import deepcopy, copy 
    import operator
    from operator import itemgetter 
    
    
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd 
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)
    def make_divisors(n, reversed=False):
        """create list of divisors
        
        Args:
            number (int): number from which list of divisors is created
            reversed (bool, optional): ascending order if False. Defaults to False.
        
        Returns:
            list: list of divisors
        """
        divisors = set()
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.add(i)
                divisors.add(n//i)
        return sorted(list(divisors),reverse=reversed)
    
    
    
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) 
    def modinv(a, p = MOD):
        
        
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        
        
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    
    
    
    
    

    def BellmanFord(N, M, ABC, vertex_start, vertex_end, value_if_inf = -1, find_shortest = False):
        """to calculate furthest or shortest length between vertex_start and vertex_end using BellmanFord algorithm
        
        Args:
            N (int): number of vertices
            M (int): number of edges
            ABC (list): [(ai, bi, ci) for _ in range(N)] where i-th edge is directed from vertex ai to vertex bi and the length is ci 
            vertex_start (int): start vertex. usually use 0.
            vertex_end (int): end vertex. usually use N-1.
            value_if_inf (int or string as you like, optional): value you want when the furthest (or shortest) distance is infinite (or -infinite). Defaults to -1.
            find_shortest (bool, optional): choose False to find furthest path. Defaults to False.
        
        Returns:
            int or string: normally int (but can be str if you set value_if_inf to str)
            
        Example:
                N, M, P = R()
                ABC = [R() for _ in range(M)]
                ABC = [(a-1, b-1, c-P) for a, b, c in ABC]
                print(BellmanFord(N, M, ABC, 0, N-1, value_if_inf = 'inf'))

        """

        def make_reachable_list(N, M, ABC, vertex_start, vertex_end):
            reachable_to_direct = defaultdict(list)
            reachable_from_direct = defaultdict(list)
            reachable_from_start = [False] * N
            reachable_to_end = [False] * N
            reachable_from_start[vertex_start] = True
            reachable_to_end[vertex_end] = True
            reachable_from_both_sides = [False] * N
            dfs_from_start = []
            dfs_to_end = []
            for a, b, c in ABC:
                reachable_to_direct[a].append(b)
                reachable_from_direct[b].append(a)
                if a == vertex_start:
                    dfs_from_start.append(b)
                    reachable_from_start[b] = True
                if b == vertex_end:
                    dfs_to_end.append(a)
                    reachable_to_end[a] = True
            while dfs_from_start:
                v = dfs_from_start.pop()
                for i in reachable_to_direct[v]:
                    if not reachable_from_start[i]:
                        reachable_from_start[i] = True
                        dfs_from_start.append(i)
            while dfs_to_end:
                v = dfs_to_end.pop()
                for i in reachable_from_direct[v]:
                    if not reachable_to_end[i]:
                        reachable_to_end[i] = True
                        dfs_to_end.append(i)
            for i in range(N):
                reachable_from_both_sides[i] = reachable_from_start[i] and reachable_to_end[i]
            return reachable_from_both_sides
        
        reachable_from_both_sides = make_reachable_list(N, M, ABC, vertex_start, vertex_end)
        
        if find_shortest:
            dist = [INF for i in range(N)]
        else:
            dist = [-INF for i in range(N)]
        
        dist[vertex_start] = 0
        for i in range(N):
            updated = False
            for a, b, c in ABC:
                if not reachable_from_both_sides[a]:
                    continue
                elif find_shortest:
                    update_condition = dist[a] + c < dist[b]
                else:
                    update_condition = dist[a] + c > dist[b]
                if dist[a] != INF and update_condition:
                    dist[b] = dist[a] + c
                    updated = True
                    if i == N-1:
                        return value_if_inf
            if not updated:
                break
        return dist[vertex_end]

    """ initialize variables and set inputs
    
        
        
            
            
    
        
        
        
        
        
        
        
    
        
        
        
        
    
        
        
    """

    
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    r_float = lambda: float(r())
    R = lambda: list(map(int, r().split()))
    R_map = lambda: map(int, r().split())
    R_float = lambda: list(map(float, r().split()))
    R_tuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    
    
    
    
    
    
    
    """

    
    if sample_file:
        sys.stdin = open(sample_file)
        
    
    
    from operator import sub
    H, W = R()
    A  = [R() for _ in range(H)]
    B  = [R() for _ in range(H)]
    AB = [list(map(lambda m, n: abs(m-n), a, b)) for (a, b) in zip(A, B)]

    dp = [[[0]*12403 for w in range(W+1)] for h in range(H+1)]
    dp[0][0][0] = 1
    for h in range(H):
        for w in range(W):
            ab = AB[h][w]
            for i in range(6401):
                
                if dp[h][w][i] == 1:
                    dp[h+1][w][i+ab] = 1
                    dp[h+1][w][abs(i-ab)] = 1
                    dp[h][w+1][i+ab] = 1
                    dp[h][w+1][abs(i-ab)] = 1
    for i in range(1000):
        if dp[H-1][W][i] == 1:
            print(i)
            return
    
    
    
    

    """memo: how to use defaultdict of list
    
    Dic = defaultdict(list)
    
    Dic[x].append(y)
    
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    
    >>> a = 5
    >>> bin_str_a = format(a, '
    >>> print(bin_str_a)
    0b0101 
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()

Solution (Python):
import numpy as np

H,W = map(int,input().split())

A = np.array(tuple(tuple(map(int,input().split())) for _ in range(H)))
B = np.array(tuple(tuple(map(int,input().split())) for _ in range(H)))

D = np.abs(A-B)
del A,B

if W > H:
    W,H = H,W
    D = D.T

L = D.max()*(H+W-1)+1
dp0 = np.zeros((W,L), dtype=bool)
dp1 = np.zeros_like(dp0)

dp1[0,D[0,0]] = True
for y in range(H):
    for x,d in enumerate(D[y]):
        dp1[x,d:] |= dp0[x,:L-d]
        dp1[x,:L-d] |= dp0[x,d:]
        dp1[x,:d] |= dp0[x,d:0:-1]
        dp1[x,d:] |= dp1[x-1,:L-d]
        dp1[x,:L-d] |= dp1[x-1,d:]
        dp1[x,:d] |= dp1[x-1,d:0:-1]
    dp0,dp1 = dp1, dp0
    dp1.fill(False)

print(next(i for i,v in enumerate(dp0[-1]) if v))

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

H,W = map(int,readline().split())
A = [list(map(int,readline().split())) for _ in range(H)]
B = [list(map(int,readline().split())) for _ in range(H)]

X = (H + W) * 80

dp = [[0] * W for _ in range(H)]
d = abs(A[0][0] - B[0][0])
dp[0][0] = (1 << (X - d))
for h in range(H):
    for w,(a,b) in enumerate(zip(A[h],B[h])):
        if h == w == 0:
            continue
        d = abs(a - b)
        x = 0
        if h != 0:
            x |= (dp[h-1][w] << d) 
            x |= (dp[h-1][w] >> d)
        if w != 0:
            x |= (dp[h][w-1] << d) 
            x |= (dp[h][w-1] >> d)
        dp[h][w] = x

dp = dp[-1][-1]

B = bin(dp)[2:]
can_make = [i - X for i,b in enumerate(B[::-1]) if b == '1']

answer = min(x if x >= 0 else -x for x in can_make)
print(answer)

Solution (Python):
import itertools
import os
import sys

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7






H, W = list(map(int, sys.stdin.buffer.readline().split()))
A = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(H)]
B = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(H)]

A = np.array(A, dtype=int)
B = np.array(B, dtype=int)
grid = np.abs(A - B).tolist()

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

dp[0][0] = 1 << (grid[0][0] + (80 * 40 * 40))
for h, w in itertools.product(range(H), range(W)):
    g = grid[h][w]
    if h - 1 >= 0:
        dp[h][w] |= dp[h - 1][w] << grid[h][w]
        dp[h][w] |= dp[h - 1][w] >> grid[h][w]
    if w - 1 >= 0:
        dp[h][w] |= dp[h][w - 1] << grid[h][w]
        dp[h][w] |= dp[h][w - 1] >> grid[h][w]

i = 0
n = dp[-1][-1] >> (80 * 40 * 40)
while True:
    if n & 1:
        print(i)
        break
    n >>= 1
    i += 1

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

diff = [[0]*(w) for i in range(h)]
for i in range(h):
    for j in range(w):
        diff[i][j] = abs(a[i][j] - b[i][j])

dp = [0] * (h*w)
dp[0] |= 1 << (13000 + diff[0][0])
dp[0] |= 1 << (13000 - diff[0][0])

for k in range(h*w):
    i = k // w
    j = k % w
    if i+1 < h:
        tmp1 = diff[i+1][j]
        dp[k + w] |= dp[k] << tmp1
        dp[k + w] |= dp[k] >> tmp1       
    if j+1 < w:
        tmp2 = diff[i][j+1]
        dp[k + 1] |= dp[k] << tmp2
        dp[k + 1] |= dp[k] >> tmp2


ans = 10**9
for i in range(81):
    if dp[w*h - 1] >> 13000 + i & 1:
        ans = min(ans, i)
for i in range(81):
    if dp[w*h - 1] >> 13000 - i & 1:
        ans = min(ans, i) 
print(ans)

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    h,w = LI()
    a = LIR(h)
    b = LIR(h)
    for i in range(h):
        for j in range(w):
            a[i][j] -= b[i][j]
            if a[i][j] < 0:
                a[i][j] *= -1
    d = [(0,1),(1,0)]
    f = [0 for x in range(w)]
    M = (1<<25600)-1
    b = 12800
    f[0] = (1<<(b+a[0][0]))|(1<<(b-a[0][0]))
    for y in range(h):
        ny = y+1
        nf = [0 for x in range(w)]
        for x in range(w):
            nx = x+1
            if nx < w:
                f[nx] |= ((f[x]<<a[y][nx])|(f[x]>>a[y][nx]))
                f[nx] &= M
            if ny < h:
                nf[x] |= ((f[x]<<a[ny][x])|(f[x]>>a[ny][x]))
                nf[x] &= M
        if ny < h:
            f = [i for i in nf]
    ans = bin(f[w-1])[2:]
    ans = [abs(i-b) for i in range(len(ans)) if ans[len(ans)-i-1] == "1"]
    print(min(ans))
    return


if __name__ == "__main__":
    solve()

Solution (Python):

import sys
input = sys.stdin.readline
MAX_VAL = 12800
 
h, w = [int(item) for item in input().split()]
a = []
b = []
for i in range(h):
    line = [int(item) for item in input().split()] + [0]
    a.append(line)
a.append([0] * (w + 1))
for i in range(h):
    line = [int(item) for item in input().split()] + [0]
    b.append(line)
b.append([0] * (w + 1))
 

dp = [[0] * (w+1) for _ in range(h+1)] 
delta = abs(a[0][0] - b[0][0])
dp[0][0] |= 1 << (MAX_VAL + delta)
dp[0][0] |= 1 << (MAX_VAL - delta)
for i in range(h):
    for j in range(w):
        diffr = abs(a[i][j+1] - b[i][j+1])
        diffd = abs(a[i+1][j] - b[i+1][j])
        
        add_delta = dp[i][j] << diffr
        sub_delta = dp[i][j] >> diffr
        dp[i][j+1] |= add_delta | sub_delta
        
        add_delta = dp[i][j] << diffd
        sub_delta = dp[i][j] >> diffd
        dp[i+1][j] |= add_delta | sub_delta
ans = MAX_VAL
for i in range(MAX_VAL * 2):
    if dp[h-1][w-1] & (1 << i):
        ans = min(ans, abs(i - MAX_VAL))
print(ans)

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    h,w = LI()
    a = LIR(h)
    b = LIR(h)
    for i in range(h):
        for j in range(w):
            a[i][j] -= b[i][j]
            if a[i][j] < 0:
                a[i][j] *= -1
    d = [(0,1),(1,0)]
    f = [0 for x in range(w)]
    M = (1<<25600)-1
    b = 12800
    f[0] = (1<<(b+a[0][0]))|(1<<(b-a[0][0]))
    for y in range(h):
        ny = y+1
        nf = [0 for x in range(w)]
        for x in range(w):
            nx = x+1
            if nx < w:
                f[nx] |= ((f[x]<<a[y][nx])|(f[x]>>a[y][nx]))
            if ny < h:
                nf[x] |= ((f[x]<<a[ny][x])|(f[x]>>a[ny][x]))
        if ny < h:
            f = [i for i in nf]
    ans = bin(f[w-1])[2:]
    ans = [abs(i-b) for i in range(len(ans)) if ans[len(ans)-i-1] == "1"]
    print(min(ans))
    return


if __name__ == "__main__":
    solve()

Solution (Python):
import numpy as np

H,W = map(int,input().split())

A = np.array(tuple(tuple(map(int,input().split())) for _ in range(H)))
B = np.array(tuple(tuple(map(int,input().split())) for _ in range(H)))

D = np.abs(A-B)
del A,B

if W > H:
    W,H = H,W
    D = D.T

L = D.max()*(H+W-1)+1
dp0 = np.zeros((W,L), dtype=bool)
dp1 = np.zeros_like(dp0)

dp1[0,D[0,0]] = True
for y in range(H):
    for x in range(W):
        d = D[y,x]

        dp1[x,d:] |= dp0[x,:L-d]
        dp1[x,:L-d] |= dp0[x,d:]
        dp1[x,:d] |= dp0[x,d:0:-1]
        dp1[x,d:] |= dp1[x-1,:L-d]
        dp1[x,:L-d] |= dp1[x-1,d:]
        dp1[x,:d] |= dp1[x-1,d:0:-1]
    dp0,dp1 = dp1, np.zeros_like(dp1)

print(min(i for i,v in enumerate(dp0[-1]) if v))