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:
from sys import stdout
import numpy as np
printn = lambda x: stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
DBG = True  and False
BIG = 999999999
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

M = 8001
K = 4000
h,w = inm()
#dp = [ [[0]*M for j in range(w)] for i in range(h) ]
dp = np.zeros((h,w,M))

a = []
b = []
for i in range(h):
    a.append(inl())
for i in range(h):
    b.append(inl())

dp[0][0][a[0][0]-b[0][0]+K] = 1
dp[0][0][-a[0][0]+b[0][0]+K] = 1

for i in range(0,h):
  for j in range(0,w):
    for u in range(M):
        if not (j>0 and dp[i][j-1][u]==1 or i>0 and dp[i-1][j][u]==1):
            continue
        x = u + a[i][j] - b[i][j]
        y = u - a[i][j] + b[i][j]
        if 0 <= x < M:
            dp[i][j][x] = 1
        if 0 <= y < M:
            dp[i][j][y] = 1

if DBG:
    for i in range(h):
        for j in range(w):
            print("i {} j {}".format(i,j))
            print(dp[i][j][992:1009])
            print("")

mn = 999999999
for u in range(M):
    if dp[h-1][w-1][u]==1 and abs(u-K)<mn:
        mn = abs(u-K)
print(mn)

Submission status: Time Limit Exceeded

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

def main():
    H, W = map(int, input().split())
    P = W+1
    A = [list(map(int, input().split())) for _ in range(H)]
    B = [list(map(int, input().split())) for _ in range(H)]
    L = 80*80*4
    mid = L//2
    dp = [[False]*(L+1) for _ in range((W+1)*(H+1))]
    for h in range(H+1):
        dp[h*P][mid] = True
    for w in range(H+1):
        dp[w][mid] = True
    
    for h in range(H):
        for w in range(W):
            c = A[h][w] - B[h][w]
            for l in range(L+1):
                if 0 <= l-c <= L:
                    dp[(h+1)*P+w+1][l] = dp[h*P+w+1][l-c] or dp[(h+1)*P+w][l-c]
                if 0 <= l+c <= L:
                    dp[(h+1)*P+w+1][l] = dp[(h+1)*P+w+1][l] or dp[h*P+w+1][l+c] or dp[(h+1)*P+w][l+c]
    ans = 10**9
    for l in range(L+1):
        if dp[H*P+W][l]:
            ans = min(abs(l-mid), ans)
    print(ans)


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

Submission status: Time Limit Exceeded

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

h, w = [ int(v) for v in input().split() ]

diff = [[ 0 for i in range(w)] for j in range(h)]
diff2 = [ [ set([]) for i in range(w)] for j in range(h)]
for i in range(h):
    line = [ int(v) for v in input().split() ]
    for j, v in  enumerate(line):
        diff[i][j] = v

for i in range(h):
    line = [ int(v) for v in input().split() ]
    for j, v in  enumerate(line):
        diff[i][j] = abs(v - diff[i][j])

for i in range(h):
    for j in range(w):
        if i == 0:
            if j == 0:
                diff2[0][0].add(diff[i][j])
            else:
                for k in diff2[i][j-1]:
                    
                    if 0 <= k + diff[i][j] <= 6400:
                        diff2[i][j].add(k + diff[i][j])
                    if 0 <= abs(diff[i][j] - k) <= 6400:
                        diff2[i][j].add(abs(diff[i][j] - k))
        else:
            for k in diff2[i-1][j]:
                if 0 <= k + diff[i][j] <= 6400:
                    diff2[i][j].add(k + diff[i][j])
                if 0 <= abs(diff[i][j] - k) <= 6400:
                    diff2[i][j].add(abs(diff[i][j] - k))
            
            if j != 0:
                for k in diff2[i][j-1]:
                    if 0 <= k + diff[i][j] <= 6400:
                        diff2[i][j].add(k + diff[i][j])
                    if 0 <= abs(diff[i][j] - k) <= 6400:
                        diff2[i][j].add(abs(diff[i][j] - k))

print(min(list(diff2[-1][-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)]
d=[[set() for i in range(W+1)] for j in range(H+1)]
d[1][1].add(A[0][0]-B[0][0])
d[1][1].add(B[0][0]-A[0][0])
for h in range(H):
    for w in range(W):
        x=A[h][w]-B[h][w]
        for y in d[h][w+1].union(d[h+1][w]):
            d[h+1][w+1].add(y+x)
            d[h+1][w+1].add(y-x)
for i in range(99):
    if i in d[H][W] or -i in d[H][W]:
        print(i)
        exit()

Submission status: Time Limit Exceeded

Solution code:
from itertools import product

H, W = map(int, input().split())
grid_A = [list(map(int, input().split())) for _ in range(H)]
grid_B = [list(map(int, input().split())) for _ in range(H)]
diff = []
M = 0
for A, B in zip(grid_A, grid_B):
    temp = [abs(a - b) for a, b in zip(A, B)]
    M = max(max(temp), M)
    diff.append(temp)
dp = [[[False]*((H+W)*(M+1)) for _ in range(W)] for _ in range(H)]
dp[0][0][diff[0][0]] = True
for i, j in product(range(H), range(W)):
    for m in range((H+W)*(M+1)):
        if dp[i][j][m]:
            if i + 1 < H:
                d = diff[i+1][j]
                dp[i+1][j][m + d] = True
                dp[i+1][j][abs(m - d)] = True
            if j + 1 < W:
                d = diff[i][j+1]
                dp[i][j+1][m + d] = True
                dp[i][j+1][abs(m - d)] = True
for i in range((H+W)*(M+1)):
    if dp[H-1][W-1][i]:
        print(i)
        break

Submission status: Time Limit Exceeded

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

q = collections.deque()

C = [[abs(A[i][j] - B[i][j]) for j in range(W)] for i in range(H)]
M = 0
for i in range(H):
    for j in range(W):
        M = max(C[i][j], M)

dp = [[[False]*((M*(H+W)) + 1) for j in range(W)] for i in range(H)]

for i in range(H):
    for j in range(W):
        if i == 0:
            if j == 0:
                dp[i][j][C[i][j]] = True
            else:
                for m in range((H+W)*M+1):
                    if dp[i][j-1][m]:
                        dp[i][j][abs(m - C[i][j])] = True
                        dp[i][j][m+C[i][j]] = True

        else:
            if j != 0:
                for m in range((H+W)*M+1):
                    if dp[i][j-1][m]:
                        dp[i][j][abs(m - C[i][j])] = True
                        dp[i][j][m+C[i][j]] = True

            for m in range((H+W)*M+1):
                if dp[i-1][j][m]:
                    dp[i][j][abs(m - C[i][j])] = True
                    dp[i][j][m+C[i][j]] = True
for i in range((M*(H+W))+1):
    if dp[H-1][W-1][i]:
        print(i)
        break

Submission status: Time Limit Exceeded

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

def solve(H: int, W: int, A: "List[List[int]]", B: "List[List[int]]"):
    state = [[set() for w in range(W)] for h in range(H)]
    todo = deque()
    done = set()
    g = abs(A[0][0]-B[0][0])
    state[0][0].add(g)
    done.add((0, 0))
    todo.append((1, 0))
    todo.append((0, 1))

    while len(todo) > 0:
        h, w = todo.popleft()
        if (h, w) in done:
            continue
        g = abs(A[h][w]-B[h][w])
        if h-1 >= 0:
            for d in state[h-1][w]:
                state[h][w].add(d+g)
                state[h][w].add(abs(d-g))
        if w-1 >= 0:
            for d in state[h][w-1]:
                state[h][w].add(d+g)
                state[h][w].add(abs(d-g))
        if h+1 < H:
            todo.append((h+1, w))
        if w+1 < W:
            todo.append((h, w+1))
        done.add((h, w))
    print(min(state[-1][-1]))

    return


# Generated by 1.1.5 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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:
from sys import stdout
printn = lambda x: stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
DBG = True  and False
BIG = 999999999
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

M = 8001
K = 4000
h,w = inm()
dp = [ [[0]*M for j in range(w)] for i in range(h) ]

a = []
b = []
for i in range(h):
    a.append(inl())
for i in range(h):
    b.append(inl())

dp[0][0][a[0][0]-b[0][0]+K] = 1
dp[0][0][-a[0][0]+b[0][0]+K] = 1

for i in range(0,h):
  for j in range(0,w):
    for u in range(M):
        if not (j>0 and dp[i][j-1][u]==1 or i>0 and dp[i-1][j][u]==1):
            continue
        x = u + a[i][j] - b[i][j]
        y = u - a[i][j] + b[i][j]
        if 0 <= x < M:
            dp[i][j][x] = 1
        if 0 <= y < M:
            dp[i][j][y] = 1

if DBG:
    for i in range(h):
        for j in range(w):
            print("i {} j {}".format(i,j))
            print(dp[i][j][992:1009])
            print("")

mn = 999999999
for u in range(M):
    if dp[h-1][w-1][u]==1 and abs(u-K)<mn:
        mn = abs(u-K)
print(mn)

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)]
d=[[0 for i in range(w)] for j in range(h)]
for i in range(h):
    for j in range(w):
        d[i][j] = abs(a[i][j]-b[i][j])
dp=np.zeros((h,w,80*(h+w)),dtype=np.bool)
dp[0,0,d[0][0]] = True
for i in range(h):
    for j in range(w):
        for dis in range(80*(h+w)):
            if dp[i,j,dis]:
                if i+1<h:
                    dp[i+1,j,dis+d[i+1][j]]=True
                    dp[i+1,j,np.abs(dis-d[i+1][j])]=True
                if j+1<w:
                    dp[i,j+1,dis+d[i][j+1]]=True
                    dp[i,j+1,np.abs(dis-d[i][j+1])]=True
for dis in range(80*(h+w)):
    if dp[-1,-1,dis]:
        print(dis)
        break

Submission status: Time Limit Exceeded

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

h, w = map(int, input().split())
grid = [None for _ in range(h)]
poss = [[set() for x in range(w)] for y in range(h)]
tmp = [map(int, input().split()) for _ in range(h * 2)]
for i, (l1, l2) in enumerate(zip(tmp, tmp[h:])):
	grid[i] = [abs(x - y) for x, y in zip(l1, l2)]
poss[0][0].add(-grid[0][0])
poss[0][0].add(grid[0][0])
for i in range(h):
	for j in range(w - 1):
		for c in poss[i][j]:
			m = grid[i][j + 1]
			poss[i][j + 1].add(c - m)
			poss[i][j + 1].add(c + m)
	if i == h - 1:
		break
	for j in range(w):
		for c in poss[i][j]:
			m = grid[i + 1][j]
			poss[i + 1][j].add(c - m)
			poss[i + 1][j].add(c + m)
print(min(abs(x) for x in poss[-1][-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)]
d=[[0 for i in range(w)] for j in range(h)]
for i in range(h):
    for j in range(w):
        d[i][j] = abs(a[i][j]-b[i][j])
dp=np.zeros((h,w,80*150),dtype=np.bool)
dp[0,0,d[0][0]] = True
for i in range(h):
    for j in range(w):
        for dis in range(80*150):
            if dp[i,j,dis]:
                if i+1<h:
                    dp[i+1,j,dis+d[i+1][j]]=True
                    dp[i+1,j,np.abs(dis-d[i+1][j])]=True
                if j+1<w:
                    dp[i,j+1,dis+d[i][j+1]]=True
                    dp[i,j+1,np.abs(dis-d[i][j+1])]=True
for dis in range(80*150):
    if dp[-1,-1,dis]:
        print(dis)
        break

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

D = [[abs(A[h][w] - B[h][w]) for w in range(W)] for h in range(H)]
K = (max(max(D)) + 1) * (H + W)
DP = [[set() for _ in range(W + 1)] for _ in range(H + 1)]
DP[0][1].add(0)

for w in range(W):
    for h in range(H):
        for dp in DP[h][w + 1]:
            DP[h + 1][w + 1].add(abs(dp + D[h][w]))
            DP[h + 1][w + 1].add(abs(dp - D[h][w]))
        for dp in DP[h + 1][w]:
            DP[h + 1][w + 1].add(abs(dp + D[h][w]))
            DP[h + 1][w + 1].add(abs(dp - D[h][w]))

print(min(DP[H][W]))

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)]
d=[[0 for i in range(w)] for j in range(h)]
for i in range(h):
    for j in range(w):
        d[i][j] = abs(a[i][j]-b[i][j])
dp=[[[] for j in range(w)] for k in range(h)]
dp[0][0].append(d[0][0])
for i in range(h):
    for j in range(w):
        for x in dp[i][j]:
            if i+1<h:
                dp[i+1][j].append(x+d[i+1][j])
                dp[i+1][j].append(abs(x-d[i+1][j]))
            if j+1<w:
                dp[i][j+1].append(x+d[i][j+1])
                dp[i][j+1].append(abs(x-d[i][j+1]))
m=10000000
for dis in dp[-1][-1]:
    m=min(m,dis)
print(m)

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
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 = [set() for x in range(w)]
    f[0].add(a[0][0])
    f[0].add(-a[0][0])
    for y in range(h):
        nf = [set() for x in range(w)]
        for x in range(w):
            M = 160*(h+w-x-y)
            m = -M
            for t in f[x]:
                nx = x+1
                if 0 <= nx < w:
                    nt = t-a[y][nx]
                    if m <= nt <= M:
                        f[nx].add(nt)
                    nt = t+a[y][nx]
                    if m <= nt <= M:
                        f[nx].add(nt)
                ny = y+1
                if 0 <= ny < h:
                    nt = t-a[ny][x]
                    if m <= nt <= M:
                        nf[x].add(nt)
                    nt = t+a[ny][x]
                    if m <= nt <= M:
                        nf[x].add(nt)
        if y < h-1:
            f = [i for i in nf]
    ans = min([abs(i) for i in f[w-1]])
    print(ans)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
import sys

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

mod=10**9+7
# rstrip().decode('utf-8')
# map(int,input().split())
import numpy as np

def main():
	h,w=map(int,input().split())
	AB=np.array(read().split(), np.int64)
	
	
	A=AB[:h*w]
	B=AB[h*w:]
	
	A=np.reshape(A, (h,w))
	B = np.reshape(B, (h, w))
	
	G=abs(A-B)
	M=h*w*80
	
	li=[[[]for i in range(w)] for j in range(h)]
	for i in range(h):
		for j in range(w):
			if i==j==0:
				li[i][j].append(G[i][j])
			elif i==0:
				for k in li[i][j-1]:
					aa=abs(k-G[i][j])
					bb=abs(k+G[i][j])
					if aa<=M:
						li[i][j].append(aa)
					if abs(bb)<=M:
						li[i][j].append(bb)
			elif j==0:
				for k in li[i-1][j]:
					aa=abs(k-G[i][j])
					bb=abs(k+G[i][j])
					if aa<=M:
						li[i][j].append(aa)
					if abs(bb)<=M:
						li[i][j].append(bb)
			else:
				for k in li[i-1][j]:
					aa=abs(k-G[i][j])
					bb=abs(k+G[i][j])
					if aa<=M:
						li[i][j].append(aa)
					if abs(bb)<=M:
						li[i][j].append(bb)
				for k in li[i][j-1]:
					aa=abs(k-G[i][j])
					bb=abs(k+G[i][j])
					if aa<=M:
						li[i][j].append(aa)
					if abs(bb)<=M:
						li[i][j].append(bb)
			
			s=set(li[i][j])
			li[i][j]=list(s)
			
			
			
			
	print(min(li[h-1][w-1]))
	
if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

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

def solve(H: int, W: int, A: "List[List[int]]", B: "List[List[int]]"):
    M = H * W * 80 + 1
    state = [[[False for d in range(M)] for w in range(W)] for h in range(H)]
    grid = [[abs(A[h][w]-B[h][w]) for w in range(W)] for h in range(H)]
    todo = deque()
    done = set()
    state[0][0][grid[0][0]] = True
    done.add((0, 0))
    todo.append((1, 0))
    todo.append((0, 1))

    while len(todo) > 0:
        h, w = todo.popleft()
        if (h, w) in done:
            continue
        g = grid[h][w]
        if h-1 >= 0:
            for d, s in enumerate(state[h-1][w]):
                if s:
                    state[h][w][d+g] = True
                    state[h][w][abs(d-g)] = True
        if w-1 >= 0:
            for d, s in enumerate(state[h][w-1]):
                if s:
                    state[h][w][d+g] = True
                    state[h][w][abs(d-g)] = True
        if h+1 < H:
            todo.append((h+1, w))
        if w+1 < W:
            todo.append((h, w+1))
        done.add((h, w))
    for d, s in enumerate(state[H-1][W-1]):
        if s:
            print(d)
            return

    return


# Generated by 1.1.5 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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:
import sys

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

mod=10**9+7
# rstrip().decode('utf-8')
# map(int,input().split())
import numpy as np
import bisect

def main():
	h,w=map(int,input().split())
	AB=np.array(read().split(), np.int64)
	
	
	A=AB[:h*w]
	B=AB[h*w:]
	
	A=np.reshape(A, (h,w))
	B = np.reshape(B, (h, w))
	
	G=abs(A-B)
	M=h*w*80
	
	li=[[[]for i in range(w)] for j in range(h)]
	for i in range(h):
		for j in range(w):
			if i==j==0:
				li[i][j].append(G[i][j])
			elif i==0:
				for k in li[i][j-1]:
					if abs(k-G[i][j])<=M:
						li[i][j].append(abs(k-G[i][j]))
					if abs(k+G[i][j])<=M:
						li[i][j].append(abs(k + G[i][j]))
			elif j==0:
				for k in li[i-1][j]:
					if abs(k-G[i][j])<=M:
						li[i][j].append(abs(k-G[i][j]))
					if abs(k+G[i][j])<=M:
						li[i][j].append(abs(k + G[i][j]))
			else:
				for k in li[i-1][j]:
					if abs(k-G[i][j])<=M:
						li[i][j].append(abs(k-G[i][j]))
					if abs(k+G[i][j])<=M:
						li[i][j].append(abs(k + G[i][j]))
				for k in li[i][j-1]:
					if abs(k-G[i][j])<=M:
						li[i][j].append(abs(k-G[i][j]))
					if abs(k+G[i][j])<=M:
						li[i][j].append(abs(k + G[i][j]))
			
	print(min(li[h-1][w-1]))
	
if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
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)]
    Ma = [[160*min((x+y+1), (h+w-x-y-1)) for x in range(w)] for y in range(h)]
    f = [set() for x in range(w)]
    f[0].add(a[0][0])
    f[0].add(-a[0][0])
    for y in range(h):
        nf = [set() for x in range(w)]
        for x in range(w):
            for t in f[x]:
                nx = x+1
                if 0 <= nx < w:
                    M = Ma[y][nx]
                    m = -M
                    nt = t-a[y][nx]
                    if m <= nt <= M:
                        f[nx].add(nt)
                    nt = t+a[y][nx]
                    if m <= nt <= M:
                        f[nx].add(nt)
                ny = y+1
                if 0 <= ny < h:
                    M = Ma[ny][x]
                    m = -M
                    nt = t-a[ny][x]
                    if m <= nt <= M:
                        nf[x].add(nt)
                    nt = t+a[ny][x]
                    if m <= nt <= M:
                        nf[x].add(nt)
        if y < h-1:
            f = [i for i in nf]
    ans = min([abs(i) for i in f[w-1]])
    print(ans)
    return

#Solve
if __name__ == "__main__":
    solve()

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)]
d=[[0 for i in range(w)] for j in range(h)]
for i in range(h):
    for j in range(w):
        d[i][j] = abs(a[i][j]-b[i][j])
dp=np.zeros((h,w,80*160),dtype=np.bool)
dp[0,0,d[0][0]] = True
for i in range(h):
    for j in range(w):
        for dis in range(80*160):
            if dp[i,j,dis]:
                if i+1<h:
                    dp[i+1,j,dis+d[i+1][j]]=True
                    dp[i+1,j,np.abs(dis-d[i+1][j])]=True
                if j+1<w:
                    dp[i,j+1,dis+d[i][j+1]]=True
                    dp[i,j+1,np.abs(dis-d[i][j+1])]=True
for dis in range(80*160):
    if dp[-1,-1,dis]:
        print(dis)
        break

Submission status: Time Limit Exceeded

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

q = collections.deque()

C = [[abs(A[i][j] - B[i][j]) for j in range(W)] for i in range(H)]
M = 0
for i in range(H):
    for j in range(W):
        M = max(C[i][j], M)

dp = [[[False]*((M*H*W) + 1) for j in range(W)] for i in range(H)]

for i in range(H):
    for j in range(W):
        if i == 0:
            if j == 0:
                dp[i][j][C[i][j]] = True
            else:
                for m in range(M+1):
                    if dp[i][j-1][m]:
                        dp[i][j][abs(m - C[i][j])] = True
                        dp[i][j][m+C[i][j]] = True

        else:
            if j != 0:
                for m in range(M+1):
                    if dp[i][j-1][m]:
                        dp[i][j][abs(m - C[i][j])] = True
                        dp[i][j][m+C[i][j]] = True

            for m in range(M+1):
                if dp[i-1][j][m]:
                    dp[i][j][abs(m - C[i][j])] = True
                    dp[i][j][m+C[i][j]] = True
for i in range((M*H*W)+1):
    if dp[H-1][W-1][i]:
        print(i)
        break

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

D = [[abs(A[h][w] - B[h][w]) for w in range(W)] for h in range(H)]
K = (max(max(D)) + 1) * (H + W)
DP = [[[False] * K for _ in range(W + 1)] for _ in range(H + 1)]
DP[0][1][0] = True

for w in range(W):
    for h in range(H):
        for k in range(K):
            if DP[h + 1][w][k] or DP[h][w + 1][k]:
                DP[h + 1][w + 1][abs(k - D[h][w])] = True
                DP[h + 1][w + 1][abs(k + D[h][w])] = True

print(min([k for k in range(K) if DP[H][W][k]]))

Submission status: Time Limit Exceeded

Solution code:
import sys

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

mod=10**9+7
# rstrip().decode('utf-8')
# map(int,input().split())
import numpy as np
import bisect

def main():
	h,w=map(int,input().split())
	AB=np.array(read().split(), np.int64)
	
	
	A=AB[:h*w]
	B=AB[h*w:]
	
	A=np.reshape(A, (h,w))
	B = np.reshape(B, (h, w))
	
	G=abs(A-B)
	
	li=[[[]for i in range(w)] for j in range(h)]
	for i in range(h):
		for j in range(w):
			if i==j==0:
				li[i][j].append(G[i][j])
			elif i==0:
				for k in li[i][j-1]:
					li[i][j].append(abs(k-G[i][j]))
					li[i][j].append(abs(k + G[i][j]))
			elif j==0:
				for k in li[i-1][j]:
					li[i][j].append(abs(k-G[i][j]))
					li[i][j].append(abs(k + G[i][j]))
			else:
				for k in li[i-1][j]:
					li[i][j].append(abs(k-G[i][j]))
					li[i][j].append(abs(k + G[i][j]))
				for k in li[i][j-1]:
					li[i][j].append(abs(k-G[i][j]))
					li[i][j].append(abs(k + G[i][j]))
			s=set(li[i][j])
			li[i][j]=sorted(list(s))
			idx=bisect.bisect_left(li[i][j],h*w*80)
			li[i][j]=li[i][j][:idx]
			
	print(min(li[h-1][w-1]))
	
if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
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)]
    Ma = [[160*min((x+y+1), (h+w-x-y-1)) for x in range(w)] for y in range(h)]
    f = [[set() for x in range(w)] for y in range(h)]
    f[0][0].add(a[0][0])
    f[0][0].add(-a[0][0])
    for y in range(h):
        for x in range(w):
            for t in f[y][x]:
                for dy,dx in d:
                    ny = y+dy
                    nx = x+dx
                    if 0 <= ny < h and 0 <= nx < w:
                        M = Ma[ny][nx]
                        m = -M
                        nt = t-a[ny][nx]
                        if m <= nt <= M:
                            f[ny][nx].add(nt)
                        nt = t+a[ny][nx]
                        if m <= nt <= M:
                            f[ny][nx].add(nt)
    ans = min([abs(i) for i in f[h-1][w-1]])
    print(ans)
    return

#Solve
if __name__ == "__main__":
    solve()

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)]
m=80*(H+W)
d=[[[0]*m for i in range(W+1)] for j in range(H+1)]
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]
        for y in range(m):
            if d[h][w+1][y] or d[h+1][w][y]:
                d[h+1][w+1][(y+x)%m]=d[h+1][w+1][(y-x)%m]=1
for i in range(m):
    if d[H][W][i] or d[H][W][-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 i in range(h)]
b = [list(map(int, input().split())) for i in range(h)]
diff = [[0]*(w+1) for i in range(h+1)]

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

n = 2 * 80 * 80 + 1
dp = [set([]) for i in range(h*w)]
dp[0].add(diff[0][0])

for k in range(h*w):
    for cnt in dp[k]:
        i = k // w
        j = k % w
        tmp1 = diff[i+1][j]
        tmp2 = diff[i][j+1]
        if i+1 < h:
            dp[k + w].add(abs(cnt - tmp1))
            if cnt + tmp1 < n:
                dp[k + w].add(cnt + tmp1)
        if j+1 < w:
            dp[k + 1].add(abs(cnt - tmp2))
            if cnt + tmp2 < n:
                dp[k + 1].add(cnt + tmp2)

ans = 10**9
for i in dp[w*h - 1]:
    ans = min(ans, i)
print(ans)