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:
H,W = map(int,input().split())
A = [[] for i in range(H)]
B = [[] for i in range(H)]

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

D = [[abs(A[i][j] - B[i][j]) for j in range(W)] for i in range(H)]
R = 160*80
dp = [[[False for k in range(R)] for j in range(W)] for i in range(H)]
dp[0][0][D[0][0]] = True
for i in range(H):
	for j in range(W):
		for n in range(R):
			if not dp[i][j][n]:
				continue
			if j != W-1:
				d = D[i][j+1]
				dp[i][j+1][n+d] = True
				dp[i][j+1][abs(n-d)] = True
			if i != H-1:
				d = D[i+1][j]
				dp[i+1][j][n+d] = True
				dp[i+1][j][abs(n-d)] = True

h,w = H-1, W-1
for i in range(R):
	if dp[h][w][i]:
		print(i)
		exit()

Submission status: Time Limit Exceeded

Solution code:
#!/bin/bash
''':'
docker run --rm -it -v $(cd $(dirname $0) && pwd):/vo:ro pypy:3-2.4.0 /bin/bash -c "pypy3 /vo/$(basename $0) < /vo/g.inp"; exit $?
exit 0
'''
import sys

def _i(): return int(sys.stdin.readline().strip())
def _ia(): return [ int(x) for x in sys.stdin.readline().strip().split() ]

# read input
h,w = _ia()
ab = []
for _ in range(h): ab.append(_ia())
for i in range(h):
    r = ab[i]
    for j,bj in enumerate(_ia()):
        r[j] = abs(r[j] - bj)
    t = max(r)

# initialize
dp = [[None for _ in range(w)] for _ in range(h)]
dp[0][0] = {ab[0][0]}
for ij in range(1,h+w-1):
    for i in range(min(ij+1,h)):
        j = ij - i
        if j>=w: continue
        #
        x = ab[i][j]
        nxt = dp[i][j] = set()
        if i==0: ref= dp[i][j-1]
        elif j==0: ref = dp[i-1][j]
        else: ref = dp[i][j-1] | dp[i-1][j]
        #
        im = 0
        for idx in ref: nxt|= {abs(idx-x),idx+x}
            
# stdout
ref=dp[h-1][w-1]
print(min(ref))

Submission status: Time Limit Exceeded

Solution code:
#!/bin/bash
''':'
docker run --rm -it -v $(cd $(dirname $0) && pwd):/vo:ro pypy:3-2.4.0 /bin/bash -c "pypy3 /vo/$(basename $0) < /vo/g.inp"; exit $?
exit 0
'''
import sys

def _i(): return int(sys.stdin.readline().strip())
def _ia(): return [ int(x) for x in sys.stdin.readline().strip().split() ]

# read input
h,w = _ia()
ab = []
m = None
for _ in range(h): ab.append(_ia())
for i in range(h):
    r = ab[i]
    for j,bj in enumerate(_ia()):
        r[j] = abs(r[j] - bj)
    t = max(r)
    if m is None or m<t: m=t

# initialize
st = ab[0][0]
m = m * (h+w-2) + st + 1
dp = [[[False] * m for _ in range(w)] for _ in range(h)]
dp[0][0][st] = True
cnt = [ [0]*w for _ in range(h)]
cnt[0][0] = st+1
for ij in range(1,h+w-1):
    for i in range(min(ij+1,h)):
        j = ij - i
        if j>=w: continue
        #
        x = ab[i][j]
        nxt = dp[i][j]
        #
        if i==0:
            ref= dp[i][j-1]
            oft= cnt[i][j-1]
        elif j==0:
            ref = dp[i-1][j]
            oft= cnt[i-1][j]
        else:
            oft = max(cnt[i][j-1],cnt[i-1][j])
            ref = list(map(lambda x: x[0]|x[1], zip(dp[i][j-1][:oft], dp[i-1][j][:oft])))
        #
        im = 0
        for idx,tf in enumerate(ref):
            if not tf: continue
            nxt[abs(idx-x)]= True
            ix = idx + x
            nxt[ix] = True
            if im<ix: im=ix
        #
        cnt[i][j] = im + 1
            
# stdout
ref=dp[h-1][w-1]
for k in range(m):
    if ref[k]:
        print(k)
        break

Submission status: Time Limit Exceeded

Solution code:
#!/bin/bash
''':'
docker run --rm -it -v $(cd $(dirname $0) && pwd):/vo:ro pypy:3-2.4.0 /bin/bash -c "pypy3 /vo/$(basename $0) < /vo/g.inp"; exit $?
exit 0
'''
import sys

def _i(): return int(sys.stdin.readline().strip())
def _ia(): return [ int(x) for x in sys.stdin.readline().strip().split() ]

# read input
h,w = _ia()
ab = []
m = None
for _ in range(h): ab.append(_ia())
for i in range(h):
    r = ab[i]
    for j,bj in enumerate(_ia()):
        r[j] = abs(r[j] - bj)
    t = max(r)
    if m is None or m<t: m=t

# initialize
st = ab[0][0]
m = m * (h+w-2) + st + 1
dp = [[[False] * m for _ in range(w)] for _ in range(h)]
dp[0][0][st] = True
for ij in range(1,h+w-1):
    for i in range(min(ij+1,h)):
        j = ij - i
        if j>=w: continue
        #
        x = ab[i][j]
        nxt = dp[i][j]
        #
        if i==0: ref= dp[i][j-1]
        elif j==0: ref = dp[i-1][j]
        else: ref = list(map(lambda x: x[0]|x[1], zip(dp[i][j-1], dp[i-1][j])))
        #
        for i,tf in enumerate(ref):
            if not tf: continue
            nxt[abs(i-x)]= True
            nxt[i+x] = True
# stdout
ref=dp[h-1][w-1]
for k in range(m):
    if ref[k]:
        print(k)
        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)]
X = [[abs(A[i][j] - B[i][j]) for j in range(W)] for i in range(H)]
dp1 = [set() for _ in range(W)]
dp1[0].add(X[0][0])
dp2 = [set() for _ in range(W)]
for i in range(H):
  if i % 2 == 0:
    dp2 = [set() for _ in range(W)]
  else: dp1 = [set() for _ in range(W)]
  for j in range(W):
    if i % 2 == 0:
      for k in dp1[j]:
        if i + 1 < H:
          u = k + X[i + 1][j]
          v = abs(k - X[i + 1][j])
          dp2[j].add(u)
          dp2[j].add(v)
        if j + 1 < W:
          u = k + X[i][j + 1]
          v = abs(k - X[i][j + 1])
          dp1[j + 1].add(u)
          dp1[j + 1].add(v)
    else:
      for k in dp2[j]:
        if i + 1 < H:
          u = k + X[i + 1][j]
          v = abs(k - X[i + 1][j])
          dp1[j].add(u)
          dp1[j].add(v)
        if j + 1 < W:
          u = k + X[i][j + 1]
          v = abs(k - X[i][j + 1])
          dp2[j + 1].add(u)
          dp2[j + 1].add(v)
res = float("inf")
if H % 2:
  for k in dp1[-1]: res = min(k, res)
else:
  for k in dp2[-1]: res = min(k, res)
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)]
X = [[abs(A[i][j] - B[i][j]) for j in range(W)] for i in range(H)]
dp = [[set() for _ in range(W)] for _ in range(H)]
dp[0][0].add(X[0][0])
dplimit = [[0] * W for _ in range(H)]
dplimit[-1][-1] = 80
for i in range(H - 1, -1, -1):
  for j in range(W - 1, -1, -1):
    x = X[i][j]
    if i > 0: dplimit[i - 1][j] = max(dplimit[i - 1][j], dplimit[i][j] + x)
    if j > 0: dplimit[i][j - 1] = max(dplimit[i][j - 1], dplimit[i][j] + x)
for i in range(H):
  for j in range(W):
    for k in dp[i][j]:
      if i + 1 < H:
        u = k + X[i + 1][j]
        v = abs(k - X[i + 1][j])
        if u <= dplimit[i][j]: dp[i + 1][j].add(u)
        if v <= dplimit[i][j]: dp[i + 1][j].add(v)
      if j + 1 < W:
        u = k + X[i][j + 1]
        v = abs(k - X[i][j + 1])
        if u <= dplimit[i][j]: dp[i][j + 1].add(u)
        if v <= dplimit[i][j]: dp[i][j + 1].add(v)
res = float("inf")
#print(dp[1][1])
for k in dp[-1][-1]: res = min(k, res)
print(res)

Submission status: Time Limit Exceeded

Solution code:
#!/bin/bash
''':'
docker run --rm -it -v $(cd $(dirname $0) && pwd):/vo:ro pypy:3-2.4.0 /bin/bash -c "pypy3 /vo/$(basename $0) < /vo/g.inp"; exit $?
exit 0
'''
import sys

def _i(): return int(sys.stdin.readline().strip())
def _ia(): return [ int(x) for x in sys.stdin.readline().strip().split() ]

# read input
h,w = _ia()
ab = []
m = None
for _ in range(h): ab.append(_ia())
for i in range(h):
    r = ab[i]
    for j,bj in enumerate(_ia()):
        r[j] = abs(r[j] - bj)
    t = max(r)
    if m is None or m<t: m=t
#
# check
def check_update(r,k,x,m):
    k_ = abs(k-x)
    if r[k_]:
        return True
    k_ = k + x
    if k_<m and r[k_]:
        return True
    return False
    
# initialize
m = m * (h+w-2) + 1
dp = [[[False] * m for _ in range(w)] for _ in range(h)]
dp[0][0][ab[0][0]] = True
for ij in range(1,h+w-1):
    for i in range(min(ij+1,h)):
        j = ij - i
        if j>=w: continue
        #
        x = ab[i][j]
        nxt = dp[i][j]
        for k in range(m):
            k1 = abs(k-x)
            k2 = k+x
            if i>0:
                flag = check_update(dp[i-1][j],k,x,m)
                if flag:
                    nxt[k] = True
                    continue
            if j>0:
                flag = check_update(dp[i][j-1],k,x,m)
                if flag:
                    nxt[k] = True
                    continue
# stdout
ref=dp[h-1][w-1]
for k in range(m):
    if ref[k]:
        print(k)
        break

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys


def solve(H: int, W: int, A: "List[List[int]]", B: "List[List[int]]"):
    ab = [[0]*W for _ in range(H)]

    for h in range(H):
        for w in range(W):
            ab[h][w] = abs(A[h][w]-B[h][w])
    
    # i,jにいるときに作れる値
    setlist = [[set() for _ in range(W)] for _ in range(H)]
    for i in range(H):
        for j in range(W):
            if i == 0 and j == 0:
                setlist[i][j].add(ab[i][j])
                continue

            if  i == 0:
                for num in setlist[i][j-1]:
                    setlist[i][j].add(abs(num+ab[i][j]))
                    setlist[i][j].add(abs(num-ab[i][j]))
                continue

            if j == 0:
                for num in setlist[i-1][j]:
                    setlist[i][j].add(abs(num+ab[i][j]))
                    setlist[i][j].add(abs(num-ab[i][j]))
                continue                
            
            for num in setlist[i-1][j]:
                setlist[i][j].add(abs(num+ab[i][j]))
                setlist[i][j].add(abs(num-ab[i][j]))
            for num in setlist[i][j-1]:
                setlist[i][j].add(abs(num+ab[i][j]))
                setlist[i][j].add(abs(num-ab[i][j]))

    print(min(setlist[H-1][W-1]))
    return



def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    A = [[int(next(tokens)) for _ in range(W)] for _ in range(H)]  # type: "List[List[int]]"
    B = [[int(next(tokens)) for _ in range(W)] for _ in range(H)]  # type: "List[List[int]]"
    solve(H, W, A, B)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
#ABC147 E

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

h,w = LI()
a = [LI() for _ in range(h)]
b = [LI() for _ in range(h)]

dp = [[set() for _ in range(w)] for _ in range(h)]
lst = [[0]*w for _ in range(h)]
for i in range(h):
    for j in range(w):
        lst[i][j] = abs(a[i][j] - b[i][j])

dp[0][0].add(lst[0][0])
for i in range(h):
    for j in range(w):
        for k in dp[i][j]:
            if i+1 < h:
                dp[i+1][j].add(k+lst[i+1][j])
                dp[i+1][j].add(abs(k-lst[i+1][j]))
            if j+1 < w:
                dp[i][j+1].add(k+lst[i][j+1])
                dp[i][j+1].add(abs(k-lst[i][j+1]))
ans = inf
for i in dp[-1][-1]:
    ans = min(ans,i)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
#ABC147 E

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

h,w = LI()
a = [LI() for _ in range(h)]
b = [LI() for _ in range(h)]

dp = [[defaultdict(int) for _ in range(w)] for _ in range(h)]
lst = [[0]*w for _ in range(h)]
for i in range(h):
    for j in range(w):
        lst[i][j] = abs(a[i][j] - b[i][j])

dp[0][0][lst[0][0]] = 1
for i in range(h):
    for j in range(w):
        for k,_ in dp[i][j].items():
            if i+1 < h:
                dp[i+1][j][k+lst[i+1][j]] = 1
                dp[i+1][j][abs(k-lst[i+1][j])] = 1
            if j+1 < w:
                dp[i][j+1][k+lst[i][j+1]] = 1
                dp[i][j+1][abs(k-lst[i][j+1])] = 1
ans = inf
for i,_ in dp[-1][-1].items():
    ans = min(ans,i)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
#ABC147 E

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

h,w = LI()
a = [LI() for _ in range(h)]
b = [LI() for _ in range(h)]

dp = [[set() for _ in range(w)] for _ in range(h)]
dp[0][0].add((a[0][0],b[0][0]))
dp[0][0].add((b[0][0],a[0][0]))
for i in range(h):
    for j in range(w):
        for (k,l) in dp[i][j]:
            if i+1 < h:
                dp[i+1][j].add((k+a[i+1][j],l+b[i+1][j]))
                dp[i+1][j].add((k+b[i+1][j],l+a[i+1][j]))
            if j+1 < w:
                dp[i][j+1].add((k+a[i][j+1],l+b[i][j+1]))
                dp[i][j+1].add((k+b[i][j+1],l+a[i][j+1]))
ans = inf
for (i,j) in dp[-1][-1]:
    ans = min(ans,abs(i-j))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
#ABC147 E

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

h,w = LI()
a = [LI() for _ in range(h)]
b = [LI() for _ in range(h)]

dp = [[defaultdict(tuple) for _ in range(w)] for _ in range(h)]
dp[0][0][(a[0][0],b[0][0])] = 1
dp[0][0][(b[0][0],a[0][0])] = 1
for i in range(h):
    for j in range(w):
        for (k,l),m in dp[i][j].items():
            if m == 0:
                continue
            if i+1 < h:
                dp[i+1][j][(k+a[i+1][j],l+b[i+1][j])] = 1
                dp[i+1][j][(k+b[i+1][j],l+a[i+1][j])] = 1
            if j+1 < w:
                dp[i][j+1][(k+a[i][j+1],l+b[i][j+1])] = 1
                dp[i][j+1][(k+b[i][j+1],l+a[i][j+1])] = 1
ans = inf
for (i,j),_ in dp[-1][-1].items():
    ans = min(ans,abs(i-j))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

def main():
    inf = 10 ** 16
    h, w = MI()
    aa = LLI(h)
    bb = LLI(h)
    cc = [[a - b for a, b in zip(ar, br)] for ar, br in zip(aa, bb)]
    dp = [[set() for _ in range(w)] for _ in range(h)]
    dp0 = dp[0]
    dp0[0].add(abs(cc[0][0]))
    for j in range(1, w):
        c = cc[0][j]
        for a in dp0[j - 1]:
            dp0[j].add(abs(a + c))
            dp0[j].add(abs(a - c))
    for i in range(1, h):
        c = cc[i][0]
        for a in dp[i - 1][0]:
            dp[i][0].add(abs(a + c))
            dp[i][0].add(abs(a - c))
    for i in range(1, h):
        dpi=dp[i]
        dpi1=dp[i-1]
        cci=cc[i]
        for j in range(1, w):
            c = cci[j]
            for a in dpi1[j]:
                dpi[j].add(abs(a + c))
                dpi[j].add(abs(a - c))
            for a in dpi[j - 1]:
                dpi[j].add(abs(a + c))
                dpi[j].add(abs(a - c))
    print(min(dp[h-1][w-1]))
main()

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
A = [list(map(int,input().split()))for _ 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])
NUM = 10000
DP = [[[0]*NUM for i in range(W)]for j in range(H)]
DP[0][0][A[0][0]] = 1
i = 0
for j in range(W-1):
    a = A[i][j+1]
    for k in range(NUM):
        if DP[i][j][k] == 1:
            if 0 <= a-k < NUM:
                DP[i][j+1][a-k] = 1
            if 0 <= k-a < NUM:
                DP[i][j+1][k-a] = 1
            if 0 <= k+a < NUM:
                DP[i][j+1][k+a] = 1
j = 0
for i in range(H-1):
    a = A[i+1][j]
    for k in range(NUM):
        if DP[i][j][k] == 1:
            if 0 <= a-k < NUM:
                DP[i+1][j][a-k] = 1
            if 0 <= k-a < NUM:
                DP[i+1][j][k-a] = 1
            if 0 <= k+a < NUM:
                DP[i+1][j][k+a] = 1
for i in range(H-1):
    for j in range(W-1):
        a = A[i+1][j+1]
        for k in range(NUM):
            if DP[i+1][j][k] == 1:
                if 0 <= a-k < NUM:
                    DP[i+1][j+1][a-k] = 1
                if 0 <= k-a < NUM:
                    DP[i+1][j+1][k-a] = 1
                if 0 <= k+a < NUM:
                    DP[i+1][j+1][k+a] = 1
            if DP[i][j+1][k] == 1:
                if 0 <= a-k < NUM:
                    DP[i+1][j+1][a-k] = 1
                if 0 <= k-a < NUM:
                    DP[i+1][j+1][k-a] = 1
                if 0 <= k+a < NUM:
                    DP[i+1][j+1][k+a] = 1

print(DP[-1][-1].index(1))

Submission status: Time Limit Exceeded

Solution code:
def balanced_path(H: int, W: int, A: list, B: list)->int:
    # M = max(
    #     abs(A[i][j] - B[i][j])
    #     for i in range(H) for j in range(W)
    # ) * (H+W-1)

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

    for h in range(H):
        for w in range(W):
            # for k in range(M+1):
            for k in dp[h][w]:
                # if not dp[h][w][k]:
                #     continue
                if h+1 < H:
                    s0 = abs(A[h+1][w]-B[h+1][w])

                    s1 = k+s0
                    dp[h+1][w].add(s1)
                    # if s1 < M+1:
                    #     dp[h+1][w][s1] = True

                    s2 = abs(k-s0)
                    dp[h+1][w].add(s2)
                    # if s2 < M+1:
                    #     dp[h+1][w][s2] = True

                if w+1 < W:
                    s0 = abs(A[h][w+1]-B[h][w+1])

                    s1 = k+s0
                    dp[h][w+1].add(s1)
                    # if s1 < M+1:
                    #     dp[h][w+1][s1] = True

                    s2 = abs(k-s0)
                    dp[h][w+1].add(s2)
                    # if s2 < M+1:
                    #     dp[h][w+1][s2] = True

    # for k in range(M+1):
    #     if dp[H-1][W-1][k]:
    #         return k
    # for k in dp[H-1][W-1]:

    # return None
    return min(dp[H-1][W-1])


if __name__ == "__main__":
    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)]

    ans = balanced_path(H, W, A, B)
    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)]
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])
NUM = 20000
DP = [[[0]*NUM for i in range(W)]for j in range(H)]
DP[0][0][A[0][0]] = 1
i = 0
for j in range(W-1):
    a = A[i][j+1]
    for k in range(NUM):
        if DP[i][j][k] == 1:
            if 0 <= a-k < NUM:
                DP[i][j+1][a-k] = 1
            if 0 <= k-a < NUM:
                DP[i][j+1][k-a] = 1
            if 0 <= k+a < NUM:
                DP[i][j+1][k+a] = 1
j = 0
for i in range(H-1):
    a = A[i+1][j]
    for k in range(NUM):
        if DP[i][j][k] == 1:
            if 0 <= a-k < NUM:
                DP[i+1][j][a-k] = 1
            if 0 <= k-a < NUM:
                DP[i+1][j][k-a] = 1
            if 0 <= k+a < NUM:
                DP[i+1][j][k+a] = 1
for i in range(H-1):
    for j in range(W-1):
        a = A[i+1][j+1]
        for k in range(NUM):
            if DP[i+1][j][k] == 1:
                if 0 <= a-k < NUM:
                    DP[i+1][j+1][a-k] = 1
                if 0 <= k-a < NUM:
                    DP[i+1][j+1][k-a] = 1
                if 0 <= k+a < NUM:
                    DP[i+1][j+1][k+a] = 1
            if DP[i][j+1][k] == 1:
                if 0 <= a-k < NUM:
                    DP[i+1][j+1][a-k] = 1
                if 0 <= k-a < NUM:
                    DP[i+1][j+1][k-a] = 1
                if 0 <= k+a < NUM:
                    DP[i+1][j+1][k+a] = 1

print(DP[-1][-1].index(1))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
def resolve():
    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 for _ in range(h)]
    x=abs(A[0][0]-B[0][0])
    dp[0][0]|=1<<x

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

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

Submission status: Time Limit Exceeded

Solution code:
def balanced_path(H: int, W: int, A: list, B: list)->int:
    M = max(
        abs(A[i][j] - B[i][j])
        for i in range(H) for j in range(W)
    ) * (H+W-1)

    dp = [[[False] * (M+1) for _ in range(W)] for _ in range(H)]
    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(M+1):
                if not dp[h][w][k]:
                    continue
                if h+1 < H:
                    s0 = abs(A[h+1][w]-B[h+1][w])

                    s1 = k+s0
                    if s1 < M+1:
                        dp[h+1][w][s1] = True

                    s2 = abs(k-s0)
                    if s2 < M+1:
                        dp[h+1][w][s2] = True

                if w+1 < W:
                    s0 = abs(A[h][w+1]-B[h][w+1])

                    s1 = k+s0
                    if s1 < M+1:
                        dp[h][w+1][s1] = True

                    s2 = abs(k-s0)
                    if s2 < M+1:
                        dp[h][w+1][s2] = True

    for k in range(M+1):
        if dp[H-1][W-1][k]:
            return k
    return None


if __name__ == "__main__":
    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)]

    ans = balanced_path(H, W, A, B)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
def resolve():
    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 for _ in range(h)]
    x=abs(A[0][0]-B[0][0])
    dp[0][0]|=1<<x

    from itertools import product
    for i,j in product(range(h),range(w)):
        x=abs(A[i][j]-B[i][j])
        if(i-1>=0):
            for k,s in enumerate(bin(dp[i-1][j])[2:][::-1]):
                if(s=='1'):
                    dp[i][j]|=1<<(k+x)
                    dp[i][j]|=1<<(abs(k-x))
        if(j-1>=0):
            for k,s in enumerate(bin(dp[i][j-1])[2:][::-1]):
                if(s=='1'):
                    dp[i][j]|=1<<(k+x)
                    dp[i][j]|=1<<(abs(k-x))

    for k,s in enumerate(bin(dp[-1][-1])[2::][::-1]):
        if(s=='1'):
            print(k)
            return
resolve()

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import numpy as np
    import sys

    input = sys.stdin.readline

    h, w = map(int, input().split())
    d = [list(map(int, input().split())) for _ in range(h * 2)]
    for r in range(h):
        for c in range(w):
            d[r][c] = abs(d[r][c] - d[r + h][c])

    MaxBias = 80 * (h + w)

    dp = np.zeros(shape=(h, w, MaxBias + 1))
    dp[0, 0, d[0][0]] = 1

    for r in range(1, h):
        for bias in range(MaxBias + 1):
            if dp[r - 1, 0, bias]:
                for new_bias in abs(bias + d[r][0]), abs(bias - d[r][0]):
                    if 0 <= new_bias <= MaxBias:
                        dp[r, 0, new_bias] = 1

    for c in range(1, w):
        for bias in range(MaxBias + 1):
            if dp[0, c - 1, bias]:
                for new_bias in abs(bias + d[0][c]), abs(bias - d[0][c]):
                    if 0 <= new_bias <= MaxBias:
                        dp[0, c, new_bias] = 1

    for r in range(1, h):
        for c in range(1, w):
            for bias in range(MaxBias + 1):
                if dp[r - 1, c, bias] or dp[r, c - 1, bias]:
                    for new_bias in abs(bias + d[r][c]), abs(bias - d[r][c]):
                        if 0 <= new_bias <= MaxBias:
                            dp[r, c, new_bias] = 1

    for bias in range(MaxBias + 1):
        if dp[h - 1, w - 1, bias]:
            print(bias)
            return


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

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

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

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

SA=[[0]*W for i in range(H)]

for i in range(H):
    for j in range(W):
        SA[i][j]=abs(A[i][j]-B[i][j])

DP=[[0 for i in range(W)] for i in range(H)]

DP[0][0]=1<<SA[0][0]

def next(i,j):
    RET=[]
    if i+j<=6400:
        RET.append(i+j)
    if abs(i-j)<=6400:
        RET.append(abs(i-j))

    return RET

for i in range(H):
    for j in range(W):
        for k in range(6400):
            if 1<<k & DP[i][j]==0:
                continue
            if i+1<H:
                for r in next(k,SA[i+1][j]):
                    DP[i+1][j]|=1<<r

            if j+1<W:
                for r in next(k,SA[i][j+1]):
                    DP[i][j+1]|=1<<r
                
for i in range(6401):
    if 1<<i & DP[-1][-1]!=0:
        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)]
X = [[abs(A[i][j] - B[i][j]) for j in range(W)] for i in range(H)]
dp = [[set() for _ in range(W)] for _ in range(H)]
dp[0][0].add(X[0][0])
for i in range(H):
  for j in range(W):
    for k in dp[i][j]:
      if i + 1 < H:
        u = k + X[i + 1][j]
        v = abs(k - X[i + 1][j])
        dp[i + 1][j].add(u)
        dp[i + 1][j].add(v)
      if j + 1 < W:
        u = k + X[i][j + 1]
        v = abs(k - X[i][j + 1])
        dp[i][j + 1].add(u)
        dp[i][j + 1].add(v)
res = float("inf")
#print(dp[1][1])
for k in dp[-1][-1]: res = min(k, res)
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)]
X = [[abs(A[i][j] - B[i][j]) for j in range(W)] for i in range(H)]
dp = [[[0] * (80 * 80 * 2 + 1) for _ in range(W)] for _ in range(H)]
dp[0][0][X[0][0]] = 1
for i in range(H):
  for j in range(W):
    for k in range(80 * 3 + 1):
      if dp[i][j][k] == 0: continue
      if i + 1 < H:
        u = k + X[i + 1][j]
        v = abs(k - X[i + 1][j])
        dp[i + 1][j][u] += dp[i][j][k]
        dp[i + 1][j][v] += dp[i][j][k]
      if j + 1 < W:
        u = k + X[i][j + 1]
        v = abs(k - X[i][j + 1])
        dp[i][j + 1][u] += dp[i][j][k]
        dp[i][j + 1][v] += dp[i][j][k]
res = 80
#print(dp[1][1])
for k in range(81):
  if dp[-1][-1][k]: res = min(k, res)
print(res)

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)]
import numpy as np
d=np.zeros((H+1,W+1,80*(H+W)),dtype=bool)
d[1][1][A[0][0]-B[0][0]]=d[1][1][B[0][0]-A[0][0]]=1
for h in range(H):
    for w in range(W):
        x=A[h][w]-B[h][w]
        d[h+1][w+1]|=(np.roll(d[h][w+1],x))|(np.roll(d[h][w+1],-x))|(np.roll(d[h+1][w],x))|(np.roll(d[h+1][w],-x))
for i in range(99):
    if d[H][W][i] or d[H][W][-i]:
        print(i)
        exit()