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: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
# template


def resolve():
    ofs = 6400
    h, w = map(int, readline().split())
    a = readlines()
    A = [list(map(int, a[i].split())) for i in range(h)]
    B = [list(map(int, a[i+h].split())) for i in range(h)]
    dp = [[0]*w for _ in range(h)]
    x = abs(A[0][0]-B[0][0])
    dp[0][0] |= ((1 << (ofs+x)) | (1 << (ofs-x)))

    from itertools import product
    for i, j in product(range(h), range(w)):
        x = abs(A[i][j]-B[i][j])
        t = 0
        if(i-1 >= 0):
            t |= dp[i-1][j]
        if(j-1 >= 0):
            t |= dp[i][j-1]
        dp[i][j] |= ((t << x) | (t >> x))

    for i, s in enumerate(bin(dp[-1][-1])[-ofs-1:]):
        if(s == '1'):
            print(i)
            return


if __name__ == "__main__":
    INF = float("inf")
    MOD = 10**9+7
    resolve()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
# template


def resolve():
    ofs = 6400
    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)]
    dp = [[0]*w for _ in range(h)]
    x = abs(A[0][0]-B[0][0])
    dp[0][0] |= ((1 << (ofs+x)) | (1 << (ofs-x)))

    from itertools import product
    for i, j in product(range(h), range(w)):
        x = abs(A[i][j]-B[i][j])
        t = 0
        if(i-1 >= 0):
            t |= dp[i-1][j]
        if(j-1 >= 0):
            t |= dp[i][j-1]
        dp[i][j] |= ((t << x) | (t >> x))

    for i, s in enumerate(bin(dp[-1][-1])[-ofs-1:]):
        if(s == '1'):
            print(i)
            return


if __name__ == "__main__":
    INF = float("inf")
    MOD = 10**9+7
    resolve()

Submission status: Accepted

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

dp = [[0] * W for i in range(H)]
dp[0][0] = 1 << (abs(A[0][0] - B[0][0]) + 6400)
for i in range(H):
    for j in range(W):
        d = abs(A[i][j] - B[i][j])
        if i > 0:
            dp[i][j] |= dp[i - 1][j] << d | dp[i - 1][j] >> d
        if j > 0:
            dp[i][j] |= dp[i][j - 1] << d | dp[i][j - 1] >> d
ans = 0
res = dp[H - 1][W - 1] >> 6400
while res & 1 == 0:
    res >>= 1
    ans += 1
print(ans)

Submission status: Accepted

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


h, w = map(int, input().split())
A = []

for i in range(h):
    line = list(map(int, input().split()))
    A.append(line)

for i in range(h):
    line = list(map(int, input().split()))
    for j, num in enumerate(line):
        A[i][j] = abs(A[i][j] - num)

const = 640000
bitset = 1 << const
DP = [0]*w
DP[0] = bitset >> A[0][0]


def slide_down(y, x):
    bit = DP[x]
    delta = A[y+1][x]
    new1 = bit << delta
    new2 = bit >> delta
    DP[x] = new1 | new2


def slide_right(y, x):
    bit = DP[x]
    delta = A[y][x+1]
    new1 = bit << delta
    new2 = bit >> delta
    DP[x+1] |= new1 | new2


for y in range(h):
    for x in range(w):
        if x < w-1:
            slide_right(y, x)
        if y < h-1:
            slide_down(y, x)

ans = DP[w-1]
for i in range(81):
    if (ans >> const+i) & 1 or (ans >> const-i) & 1:
        print(i)
        exit()

Submission status: Accepted

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


h, w = map(int, input().split())
A = []

for i in range(h):
    line = list(map(int, input().split()))
    A.append(line)

for i in range(h):
    line = list(map(int, input().split()))
    for j, num in enumerate(line):
        A[i][j] = abs(A[i][j] - num)

const = 64000
bitset = 1 << const
DP = [0]*w
DP[0] = bitset >> A[0][0]


def slide_down(y, x):
    bit = DP[x]
    delta = A[y+1][x]
    new1 = bit << delta
    new2 = bit >> delta
    DP[x] = new1 | new2


def slide_right(y, x):
    bit = DP[x]
    delta = A[y][x+1]
    new1 = bit << delta
    new2 = bit >> delta
    DP[x+1] |= new1 | new2


for y in range(h):
    for x in range(w):
        if x < w-1:
            slide_right(y, x)
        if y < h-1:
            slide_down(y, x)

ans = DP[w-1]
for i in range(81):
    if (ans >> const+i) & 1 or (ans >> const-i) & 1:
        print(i)
        exit()

Submission status: Accepted

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)]
D = [[abs(A[h][w]-B[h][w]) for w in range(W)] for h in range(H)]
def cal():
    dp1 = [set() for _ in range(W)]
    dp2 = [set() for _ in range(W)]
    for h in range(H):
        for w in range(W):
            d = D[h][w]
            if h==0 and w==0:
                dp2[0].add(d)
            for v in dp1[w]:
                v1 = v+d
                v2 = v-d if v>=d else -v+d
                dp2[w].add(v1)
                dp2[w].add(v2)
            if 0 < w:
                for v in dp2[w-1]:
                    v1 = v+d
                    v2 = v-d if v>=d else -v+d
                    dp2[w].add(v1)
                    dp2[w].add(v2)
        dp1 = dp2
        dp2 = [set() for _ in range(W)]
    return min(dp1[W-1])
ans = cal()
print(ans)

Submission status: Accepted

Solution code:
H,W = map(int, input().split())
A = [[int(a) for a in input().split()] for _ in range(H)]
B = [[int(b) for b in input().split()] for _ in range(H)]

C = [[0]*W for _ in range(H)]
num = 80
for i in range(H):
    for j in range(W):
        C[i][j] = abs(A[i][j]-B[i][j])
        
dp = [[0]*W for _ in range(H)]
dp[0][0] |= (1<<num+C[0][0]) | (1<<num-C[0][0])

for i in range(H):
    for j in range(W):
        if i > 0:
            dp[i][j] |= (dp[i-1][j]<<num+C[i][j]) | (dp[i-1][j]<<num-C[i][j])
        if j > 0:
            dp[i][j] |= (dp[i][j-1]<<num+C[i][j]) | (dp[i][j-1]<<num-C[i][j])
            
b = list(bin(dp[-1][-1]))[::-1]
ans = 10**9
for i in range(len(b)):
    if b[i] == "1":
        ans = min(ans, abs(num*(H+W-1)-i))

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
H,W=map(int,input().split())
a = [[] for _ in range(H)]
for i in range(H):
    a[i] = list(map(int, input().split()))
b = [[] for _ in range(H)]
for i in range(H):
    b[i] = list(map(int, input().split()))

for i in range(H):
    for j in range(W):
        a[i][j] =abs(a[i][j]-b[i][j])

dp = [[set() for _ in range(W)] for _ in range(H)]
dp[0][0].add(a[0][0])
for i in range(1,H):
    t = a[i][0]
    tmp = set()
    for k in dp[i-1][0]:
        tmp.add(k+t)
        tmp.add(abs(k-t))
    dp[i][0] = tmp
for j in range(1,W):
    t = a[0][j]
    tmp = set()
    for k in dp[0][j-1]:
        tmp.add(k+t)
        tmp.add(abs(k-t))
    dp[0][j] = tmp
for i in range(1,H):
    for j in range(1,W):
        t = a[i][j]
        tmp = set()
        for k in (dp[i-1][j] | dp[i][j-1]):
            tmp.add(k+t)
            tmp.add(abs(k-t))
        dp[i][j] = tmp
        dp[i-1][j-1] = set()

ls = list(dp[H-1][W-1])
print(min(ls))

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[]]*num
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################

H,W = II()
A,B,C = [],[],[]
for i in range(H):
    A.append(III())
for i in range(H):
    B.append(III())
for i in range(H):
    C.append([abs(A[i][j]-B[i][j]) for j in range(W)])

def calc(n):
    return n+80*(H+W-1)

d = [[0]*W for _ in range(H)]
for i in range(H):
    for j in range(W):
        if i==0 and j==0:
            d[i][j] = 2**calc(-C[i][j]) | 2**calc(C[i][j])
        elif i==0:
            d[i][j] = (d[i][j-1]<<C[i][j]) | (d[i][j-1]>>C[i][j])
        elif j==0:
            d[i][j] = (d[i-1][j]<<C[i][j]) | (d[i-1][j]>>C[i][j])
        else:
            d[i][j] = (d[i][j-1]<<C[i][j]) | (d[i][j-1]>>C[i][j]) | \
                        (d[i-1][j]<<C[i][j]) | (d[i-1][j]>>C[i][j])

ans = (H+W-1)*80+1
for i in range(160*(H+W-1)+1):
    if (d[H-1][W-1]>>i)&1:
        val = abs(i-80*(H+W-1))
        if val<ans:
            ans = val

print(ans)

Submission status: Accepted

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


def reverse_binary(n, width):
    return int("{:0{width}b}".format(n, width=width)[::-1], 2)


dp = [[0 for _ in range(W)] for _ in range(H)]
dp[0][0] = 1 << abs(A[0][0] - B[0][0])

for h in range(H):
    for w in range(W):
        diff = abs(A[h][w] - B[h][w])
        if w:
            dp[h][w] |= (reverse_binary(dp[h][w - 1] & ((1 << diff) - 1), diff)) << 1
            dp[h][w] |= dp[h][w - 1] >> diff
            dp[h][w] |= dp[h][w - 1] << diff
        if h:
            dp[h][w] |= (reverse_binary(dp[h - 1][w] & ((1 << diff) - 1), diff)) << 1
            dp[h][w] |= dp[h - 1][w] >> diff
            dp[h][w] |= dp[h - 1][w] << diff

tmp = dp[-1][-1]
ans = 0
while tmp & 1 == 0:
    tmp >>= 1
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
def main():
    H, W = [int(i) for i in 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)]
    M = (H + W) * 80 + 1

    u = [[False] * M for _ in range(W)]
    v = [[False] * M for _ in range(W)]
    F = [False] * M
    v[0][0] = True
    for h in range(H):
        v, u = u, v
        vl = F
        for w in range(W):
            a, b = A[h][w], B[h][w]
            d = a - b if a > b else b - a
            uu = u[w]
            vv = v[w]
            for i in range(M):
                di = i - d if i > d else d - i
                vv[i] = ((i + d < M and (uu[i + d] or vl[i + d])) or
                           (uu[di] or vl[di]))
            vl = vv
    va = v[-1]
    for i in range(M):
        if va[i]:
            print(i)
            return
    raise

main()

Submission status: Accepted

Solution code:
import numpy as np

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

A = []
B = []

max_bias = 80
bias = max_bias * (H + W - 1) + 1

for i in range(H):
    A.append(list(map(int, input().split())))

for i in range(H):
    B.append(list(map(int, input().split())))

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

dp = np.zeros([H, W, bias * 2 + 1], dtype=bool)
dp[0][0][bias - D[0][0]] = True
dp[0][0][bias + D[0][0]] = True

for i in range(H):
    for j in range(W):
        diff = D[i][j]
        
        if i > 0:
            dp[i, j, diff:] |= dp[i - 1, j, :bias * 2 + 1 - diff]
            dp[i, j, : bias * 2 + 1 - diff] |= dp[i - 1, j, diff:]

        if j > 0:
            dp[i, j, diff:] |= dp[i, j - 1, :bias * 2 + 1 - diff]
            dp[i, j, : bias * 2 + 1 - diff] |= dp[i, j - 1, diff:]

idx = dp[H - 1][W - 1][:].nonzero()[0]
print(np.abs(idx - bias).min())

Submission status: Accepted

Solution code:
import time
start = time.time()
H,W=[int(s) for s in input().split()]
inls=[[int(s) for s in input().split()] for _ in range(H)]
for i in range(H):
  x=[int(s) for s in input().split()]
  for j in range(W):
    inls[i][j]=abs(inls[i][j]-x[j])
dp=[[set() for _ in range(W)] for _ in range(H)]
dp[0][0].add(inls[0][0])
for i in range(H):
  for j in range(W):
    x=80*(H+W-i-j)
    for e in dp[i-1][j]:
      if e+inls[i][j]<x:
        dp[i][j].add(e+inls[i][j])
      dp[i][j].add(abs(e-inls[i][j]))
    for e in dp[i][j-1]:
      if e+inls[i][j]<x:
        dp[i][j].add(e+inls[i][j])
      dp[i][j].add(abs(e-inls[i][j]))
  if time.time() - start>1.7:
    dp[H-1][W-1].add(0)
    break
print(min(dp[H-1][W-1]))

Submission status: Accepted

Solution code:
# input
h, w = map(int, input().split())

alist = [list(map(int, input().split())) for i in range(h)]
blist = [list(map(int, input().split())) for i in range(h)]

# process
dlist = [[0]*w for i in range(h)]
for i in range(h):
    for j in range(w):
        dlist[i][j] = (abs(alist[i][j] - blist[i][j]))

l = [[0]*w for i in range(h)]
l[0][0] = (1<<80+dlist[0][0]) | (1<<80-dlist[0][0])
for i in range(h):
    for j in range(w):
        if i > 0:
            l[i][j] |= l[i-1][j]<<80+dlist[i][j] 
            l[i][j] |= l[i-1][j]<<80-dlist[i][j]
        if j > 0:
            l[i][j] |= l[i][j-1]<<80+dlist[i][j] 
            l[i][j] |= l[i][j-1]<<80-dlist[i][j]

dblist=list(bin(l[h-1][w-1]))[::-1]
m = 80*(h+w-1)
ans = m
for i in range(len(dblist)):
    if dblist[i] == "1":
        ans = min(ans, abs(m-i))

# output
print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


h, w = LI()
A = LIR(h)
B = LIR(h)
dp = [[0] * w for _ in range(h)]
m = 80 * 160
dp[0][0] = (1 << m) << abs(A[0][0] - B[0][0])
dp[0][0] |= (1 << m) >> abs(A[0][0] - B[0][0])
for y in range(h):
    for x in range(w):
        if y + 1 < h:
            dp[y + 1][x] |= dp[y][x] << abs(A[y + 1][x] - B[y + 1][x])
            dp[y + 1][x] |= dp[y][x] >> abs(A[y + 1][x] - B[y + 1][x])
        if x + 1 < w:
            dp[y][x + 1] |= dp[y][x] << abs(A[y][x + 1] - B[y][x + 1])
            dp[y][x + 1] |= dp[y][x] >> abs(A[y][x + 1] - B[y][x + 1])


ans = INF
for j in range(m * 2):
    if dp[h - 1][w - 1] >> j & 1:
        ans = min(ans, abs(j - m))


print(ans)

Submission status: Accepted

Solution code:
import sys
def main():
    input = sys.stdin.readline
    H, W = map(int, input().split())
    A = []
    B = []
    M = 80 * (H + W)
    for _ in range(H):
        a = tuple(map(int, input().split()))
        A.append(a)
    for _ in range(H):
        b = tuple(map(int, input().split()))
        B.append(b)
    AB = [[0] * W for _ in range(H)]
    for i in range(H):
        for j in range(W):
            AB[i][j] = abs(A[i][j] - B[i][j])
    l = [set([]) for _ in range(W)]
    lt = [set([]) for _ in range(W)]
    for i in range(H):
        for j in range(W):
            if i == 0 and j == 0:
                lt[j].add(AB[0][0])
            else:
                t = AB[i][j]
                if i > 0:
                    for k in l[j]:
                        lt[j].add(k+t)
                        lt[j].add(abs(k-t))
                if j > 0:
                    for k in lt[j-1]:
                        lt[j].add(k+t)
                        lt[j].add(abs(k-t))
        l = lt
        lt = [set([]) for _ in range(W)]
    return min(l[-1])
print(main())

Submission status: Accepted

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)]
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=[[0]*w for i in range(h)]
m=80
dp[0][0] = (1<<m+C[0][0]) | (1<<m-C[0][0])

for i in range(h):
    for j in range(w):
        if i>=1:
            dp[i][j] |= (dp[i-1][j]<<m+C[i][j]) | (dp[i-1][j]<<m-C[i][j])
        if j>=1:
            dp[i][j] |= (dp[i][j-1]<<m+C[i][j]) | (dp[i][j-1]<<m-C[i][j])
            
b=list(bin(dp[h-1][w-1]))[::-1]
ans=float("inf")

for i in range(len(b)):
    if b[i]=="1":
        ans=min(ans,abs(m*(h+w-1)-i))

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
import numpy as np
inf = float('inf')

H, W = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(H)]
A = np.array(A)
B = [list(map(int,input().split())) for _ in range(H)]
B = np.array(B)
D = A - B
D = np.vectorize(abs)(D)

N = (H + W) * 80
M = 2*N + 1
# [-N, N] を [0,2*N] として扱う(右にNだけずらす)
dp = [[np.zeros(M, np.bool) for _ in range(W)] for _ in range(H)]
d = D[0][0]
dp[0][0][d+N] = 1
dp[0][0][-d+N] = 1

for i, Di in enumerate(D):
    for j, Dij in enumerate(Di):
        if i != 0:
            dp[i][j][Dij:M] |= dp[i-1][j][0:M-Dij]
            dp[i][j][0:M-Dij] |= dp[i-1][j][Dij:M]
        if j != 0:
            dp[i][j][Dij:M] |= dp[i][j-1][0:M-Dij]
            dp[i][j][0:M-Dij] |= dp[i][j-1][Dij:M]

ind = np.where(dp[H-1][W-1])[0]
ind -= N
ans = np.vectorize(abs)(ind).min()
print(ans)

Submission status: Accepted

Solution code:
def p_e():
    h, w = map(int, input().split())
    t1 = [list(map(int, input().split())) for _ in range(h)]
    t2 = [list(map(int, input().split())) for _ in range(h)]
 
    # pythonでbitsetを用いる->boolのDPで2進数の1をTrue, 0をFalseとして扱う
    # 右にxシフト = その値にx足した値    (10001)<<4 -> (100010000)
    m = 160 * 80
    dp = [[0] * w for _ in range(h)]
    dp[0][0] = 1 << m
    for i in range(h):
        for j in range(w):
            v = abs(t1[i][j] - t2[i][j])
            if i > 0:
                dp[i][j] |= dp[i - 1][j]
            if j > 0:
                dp[i][j] |= dp[i][j - 1]
            dp[i][j] = (dp[i][j] << v) | (dp[i][j] >> v)
 
    ans = m
    for i in range(m * 2):
        if dp[h - 1][w - 1] & (1 << i) > 0:
            ans = min(ans, abs(m - i))
    print(ans)
    
p_e()

Submission status: Accepted

Solution code:
def p_e():
    from itertools import product
    h, w = map(int, input().split())
    t1 = [list(map(int, input().split())) for _ in range(h)]
    t2 = [list(map(int, input().split())) for _ in range(h)]

    # pythonでbitsetを用いる->boolのDPで2進数の1をTrue, 0をFalseとして扱う
    # 右にxシフト = その値にx足した値    (10001)<<4 -> (100010000)
    m = 160 * 80
    dp = [[0] * w for _ in range(h)]
    dp[0][0] = 1 << m
    for i, j in product(range(h), range(w)):
        v = abs(t1[i][j] - t2[i][j])
        if i > 0:
            dp[i][j] |= dp[i - 1][j]
        if j > 0:
            dp[i][j] |= dp[i][j - 1]
        dp[i][j] = (dp[i][j] << v) | (dp[i][j] >> v)

    ans = m
    for i in range(m * 2):
        if dp[h - 1][w - 1] & (1 << i) > 0:
            ans = min(ans, abs(m - i))
    print(ans)
    
p_e()

Submission status: Accepted

Solution code:
import sys
def main():
  input = sys.stdin.readline
  h, w = map(int, input().split())
  A = []
  AB = []
  A_append = A.append
  AB_append = AB.append
  for i in range(h):
    row = list(map(int, input().split()))
    A_append(row)
  for i in range(h):
    row = [abs(A[i][j] - int(b)) for j, b in enumerate(input().split())]
    AB_append(row)
 
  dp_cur = [set([]) for _ in range(w)]
  dp_cur[0].add(AB[0][0])
  for i in range(h):
    dp_next = [set([]) for _ in range(w)]
    for j in range(w):
      if j < w - 1:
        add1 = dp_cur[j+1].add
        dif1 = AB[i][j+1]
      if i < h - 1:
        add2 = dp_next[j].add
        dif2 = AB[i+1][j]
      for item in dp_cur[j]:
        if j < w - 1:
          add1(item+dif1)
          add1(abs(item-dif1))
        if i < h - 1:
          add2(item+dif2)
          add2(abs(item-dif2))
    if i == h - 1:
      break
    dp_cur = dp_next
  print(min(dp_cur[w-1]))
if __name__ == '__main__':
  main()

Submission status: Accepted

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 = [list(map(int,readline().split())) for _ in range(H)]
B = [list(map(int,readline().split())) for _ in range(H)]
 
X = (H + W) * 80
# X点持った状態から始める
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)

Submission status: Accepted

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

AB = [list(map(lambda x, y: abs(x - y), a, b)) for a, b in zip(A, B)]
dp = [[[0] * 12801 for _ in range(W + 1)] for _ 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(10000):
            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][W-1][i] == 1:
        print(i)
        break

Submission status: Accepted

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

def main():
	h, w = map(int, input().split())
	a = [map(int, input().split()) for _ in range(h)]
	b = [map(int, input().split()) for _ in range(h)]
	g = [list(abs(x - y) for x, y in zip(l1, l2)) for l1, l2 in zip(a, b)]
	poss = [0] * w
	poss[0] |= 1 << 6400 + g[0][0]
	poss[0] |= 1 << 6400 - g[0][0]
	for i in range(h):
		for j in range(w):
			if j < w - 1:
				d = g[i][j + 1]
				poss[j + 1] |= poss[j] << d
				poss[j + 1] |= poss[j] >> d
			if i < h - 1:
				d = g[i + 1][j]
				poss[j] = poss[j] << d | poss[j] >> d
	res = poss[-1]
	for i in range(6400):
		if res & (1 << 6400 + i) or res & (1 << 6400 - i):
			print(i)
			exit()

if __name__ == "__main__":
	main()

Submission status: Accepted

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

h, w = map(int, input().split())
a = [map(int, input().split()) for _ in range(h)]
b = [map(int, input().split()) for _ in range(h)]
g = [list(abs(x - y) for x, y in zip(l1, l2)) for l1, l2 in zip(a, b)]
poss = [[0] * w for _ in range(h)]
poss[0][0] |= 1 << 6400 + g[0][0]
poss[0][0] |= 1 << 6400 - g[0][0]
for i in range(h):
	for j in range(w - 1):
		poss[i][j + 1] |= poss[i][j] << g[i][j + 1]
		poss[i][j + 1] |= poss[i][j] >> g[i][j + 1]
	if i != h - 1:
		for j in range(w):
			poss[i + 1][j] |= poss[i][j] << g[i + 1][j]
			poss[i + 1][j] |= poss[i][j] >> g[i + 1][j]
res = poss[-1][-1]
for i in range(6400):
	if res & (1 << 6400 + i) or res & (1 << 6400 - i):
		print(i)
		exit()

Submission status: Accepted

Solution code:
R, C = map(int, input().split())

A = [list(map(int, input().split())) for _ in range(R)]
B = [list(map(int, input().split())) for _ in range(R)]

dp = [0] * C
dp[0] = s = 1 << 6400

for row_a, row_b in zip(A, B):
    for i, (a, b) in enumerate(zip(row_a, row_b)):
        d = abs(a - b)
        if i > 0:
            dp[i] |= dp[i - 1]
        dp[i] = (dp[i] << d) | (dp[i] >> d)

g = dp[-1]
for i in range(6401):
    if g & (s << i) or g & (s >> i):
        print(i)
        quit()

Submission status: Accepted

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 = [0] * W
dp[0] = s = 1 << 6400

for a, b in zip(A, B):
    for j, (aa, bb) in enumerate(zip(a, b)):
        d = abs(aa - bb)
        if j > 0:
            dp[j] |= dp[j - 1]
        dp[j] = (dp[j] << d) | (dp[j] >> d)

g = dp[-1]
for i in range(6401):
    if g & (s << i) or g & (s >> i):
        print(i)
        quit()

Submission status: Accepted

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


h, w = map(int, input().split())
A = []

for i in range(h):
    line = list(map(int, input().split()))
    A.append(line)

for i in range(h):
    line = list(map(int, input().split()))
    for j, num in enumerate(line):
        A[i][j] = abs(A[i][j] - num)

const = 6400
bitset = 1 << const
DP = [0]*w
DP[0] = bitset >> A[0][0]


def slide_down(y, x):
    bit = DP[x]
    delta = A[y+1][x]
    new1 = bit << delta
    new2 = bit >> delta
    DP[x] = new1 | new2


def slide_right(y, x):
    bit = DP[x]
    delta = A[y][x+1]
    new1 = bit << delta
    new2 = bit >> delta
    DP[x+1] |= new1 | new2


for y in range(h):
    for x in range(w):
        if x < w-1:
            slide_right(y, x)
        if y < h-1:
            slide_down(y, x)

ans = DP[w-1]
for i in range(81):
    if (ans >> const+i) & 1 or (ans >> const-i) & 1:
        print(i)
        exit()

Submission status: Accepted

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


h, w = map(int, input().split())
A = []

for i in range(h):
    line = list(map(int, input().split()))
    A.append(line)

for i in range(h):
    line = list(map(int, input().split()))
    for j, num in enumerate(line):
        A[i][j] = abs(A[i][j] - num)

const = 6400
bitset = 1 << const
DP = [[0]*w for _ in range(h)]
DP[0][0] = bitset >> A[0][0]


def slide_down(y, x):
    bit = DP[y][x]
    delta = A[y+1][x]
    new1 = bit << delta
    new2 = bit >> delta
    DP[y+1][x] |= new1 | new2


def slide_right(y, x):
    bit = DP[y][x]
    delta = A[y][x+1]
    new1 = bit << delta
    new2 = bit >> delta
    DP[y][x+1] |= new1 | new2


for y in range(h):
    for x in range(w):
        if y < h-1:
            slide_down(y, x)
        if x < w-1:
            slide_right(y, x)

ans = DP[h-1][w-1]
for i in range(81):
    if (ans >> const+i) & 1 or (ans >> const-i) & 1:
        print(i)
        exit()

Submission status: Accepted

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


h, w = map(int, input().split())
inf = float('INF')
A = []
B = []

for i in range(h):
    line = list(map(int, input().split()))
    A.append(line)

for i in range(h):
    line = list(map(int, input().split()))
    B.append(line)

D = [[0]*w for i in range(h)]
for i in range(h):
    for j in range(w):
        D[i][j] = abs(A[i][j] - B[i][j])


def slide_down(y, x, possible):
    new = set()
    delta = D[y+1][x]
    limit = (h+w) * 80
    for num in possible:
        if num + delta <= limit - (y+x)*80:
            new.add(num+delta)
        if abs(num-delta) <= limit - (y+x)*80:
            new.add(abs(num-delta))
    return new


def slide_right(y, x, possible):
    new = set()
    delta = D[y][x+1]
    limit = (h+w) * 80
    for num in possible:
        if num + delta <= limit - (y+x)*80:
            new.add(num+delta)
        if abs(num-delta) <= limit - (y+x)*80:
            new.add(abs(num-delta))
    return new


DP = [[set() for j in range(w)] for i in range(h)]
DP[0][0] = {D[0][0]}
for row in range(h):
    for col in range(w):
        possible = DP[row][col]
        if col < w-1:
            new = slide_right(row, col, possible)
            DP[row][col+1] |= new
        if row < h-1:
            new = slide_down(row, col, possible)
            DP[row+1][col] |= new

ans = min(DP[h-1][w-1])
print(ans)

Submission status: Accepted

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

dif = []
for aj, bj in zip(a, b):
    dif.append([abs(aij - bij) for aij, bij in zip(aj, bj)])

dp = [0] * w

dp[0] = 1 << 6400

for i in range(h):
    dp[0] = (dp[0] << dif[i][0])|(dp[0] >> dif[i][0])
    for j in range(1, w):
        dp[j] = (dp[j-1] << dif[i][j])|(dp[j-1] >> dif[i][j])|(dp[j] << dif[i][j])|(dp[j] >> dif[i][j])

result = list(format(dp[-1] >> 6400, "b"))[::-1]
ans = 0
for i in range(len(result)):
    if result[i] == "1":
        print(ans)
        break
    else:
        ans += 1

Submission status: Accepted

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

h,w =map(int,input().split())
a = [tuple(map(int,input().split())) for _ in [0]*h]
b = [tuple(map(int,input().split())) for _ in [0]*h]


mid = 1<<(80*160)
dp = [[0]*w for _ in [0]*h]

for i in range(h):
    for j in range(w):
        diff = abs(a[i][j]-b[i][j])
        new = 0
        if i > 0:
            new |= dp[i-1][j]
        if j > 0:
            new |= dp[i][j-1]
        if (i,j) == (0,0):
            new = mid
        dp[i][j] = (new<<diff)|(new>>diff)


res = 10**9
p = dp[-1][-1]
for i in range(80*321):
    if p&1 == 1:
        res = min(res,abs(80*160-i))
    p = p>> 1
print(res)