Problem:


Score : 500 points

Problem Statement

We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.

The square (i, j) has two numbers A_{ij} and B_{ij} written on it.

First, for each square, Takahashi paints one of the written numbers red and the other blue.

Then, he travels from the square (1, 1) to the square (H, W). In one move, he can move from a square (i, j) to the square (i+1, j) or the square (i, j+1). He must not leave the grid.

Let the unbalancedness be the absolute difference of the sum of red numbers and the sum of blue numbers written on the squares along Takahashi's path, including the squares (1, 1) and (H, W).

Takahashi wants to make the unbalancedness as small as possible by appropriately painting the grid and traveling on it.

Find the minimum unbalancedness possible.

Constraints

2 \leq H \leq 80

2 \leq W \leq 80

0 \leq A_{ij} \leq 80

0 \leq B_{ij} \leq 80

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W
A_{11} A_{12} \ldots A_{1W}
:
A_{H1} A_{H2} \ldots A_{HW}
B_{11} B_{12} \ldots B_{1W}
:
B_{H1} B_{H2} \ldots B_{HW}

Output

Print the minimum unbalancedness possible.

Sample Input 1

2 2
1 2
3 4
3 4
2 1

Sample Output 1

0

By painting the grid and traveling on it as shown in the figure below, the sum of red numbers and the sum of blue numbers are 3+3+1=7 and 1+2+4=7, respectively, for the unbalancedness of 0.

Sample Input 2

2 3
1 10 80
80 10 1
1 2 3
4 5 6

Sample Output 2

2



Sample input:
2 2
1 2
3 4
3 4
2 1


Sample output:
0

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
h,w=map(int,input().split())
a=[]
for i in range(h):
    a.append(list(map(int,input().split())))
b=[]
for i in range(h):
    b.append(list(map(int,input().split())))
dp=[[set([]) for i in range(w)] for j 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):
        if i==j==0:
            continue
        if i==0:
            for k in dp[i][j-1]:
                if k<=3550:
                    dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                    dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        elif j==0:
            for k in dp[i-1][j]:
                if k<=3550:
                    dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                    dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        else:
            for k in (dp[i][j-1]|dp[i-1][j]):
                if k<=6500:
                    dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                    dp[i][j].add(abs(k+b[i][j]-a[i][j]))             
#dp[h-1][w-1]
ans=10**10
for i in dp[h-1][w-1]:
    ans=min(ans,abs(i))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
h,w=map(int,input().split())
a=[]
for i in range(h):
    a.append(list(map(int,input().split())))
b=[]
for i in range(h):
    b.append(list(map(int,input().split())))
dp=[[set([]) for i in range(w)] for j 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):
        if i==j==0:
            continue
        if i==0:
            for k in dp[i][j-1]:
                if k<=6500:
                    dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                    dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        elif j==0:
            for k in dp[i-1][j]:
                if k<=6500:
                    dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                    dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        else:
            for k in (dp[i][j-1]|dp[i-1][j]):
                if k<=6500:
                    dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                    dp[i][j].add(abs(k+b[i][j]-a[i][j]))             
#dp[h-1][w-1]
ans=10**10
for i in dp[h-1][w-1]:
    ans=min(ans,abs(i))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
h,w=map(int,input().split())
a=[]
for i in range(h):
    a.append(list(map(int,input().split())))
b=[]
for i in range(h):
    b.append(list(map(int,input().split())))
dp=[[set([]) for i in range(w)] for j 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):
        if i==j==0:
            continue
        if i==0:
            for k in dp[i][j-1]:
                if k<=4000:
                    dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                    dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        elif j==0:
            for k in dp[i-1][j]:
                if k<=4000:
                    dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                    dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        else:
            for k in (dp[i][j-1]|dp[i-1][j]):
                if k<=6500:
                    dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                    dp[i][j].add(abs(k+b[i][j]-a[i][j]))             
#dp[h-1][w-1]
ans=10**10
for i in dp[h-1][w-1]:
    ans=min(ans,abs(i))
print(ans)

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())
	
	G=[[0]*w for i in range(h)]
	
	for i in range(h):
		A=list(map(int,input().split()))
		for j in range(w):
			G[i][j]+=A[j]
	for i in range(h):
		B = list(map(int, input().split()))
		for j in range(w):
			G[i][j] =abs(G[i][j]-B[j])
	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, math, itertools, heapq, collections, bisect,copy
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
sys.setrecursionlimit(10**7)
inf = float('inf')
mod = 10**9+7
ans = inf ;count = 0 ;pro = 1

h,w=map(int,input().split())
A=[tuple(map(int,input().split())) for i in range(h)]
B=[tuple(map(int,input().split())) for i in range(h)]
K = 12900
dp = [[[0]*K for j in range(w)] for i in range(h)]
dp[0][0][abs(A[0][0]-B[0][0])] = 1
for i in range(h):
    for j in range(w):
        d=abs(A[i][j]-B[i][j])
        if i-1>=0:
            for k in range(K):
                if dp[i-1][j][k]:
                    dp[i][j][k+d]=1
                    dp[i][j][abs(k-d)]=1
        if j-1>=0:
            for k in range(K):
                if dp[i][j-1][k]:
                    dp[i][j][k+d] = 1
                    dp[i][j][abs(k-d)]=1
for k in range(K):
    if dp[i][j][k]:
        print(k)
        exit()

Submission status: Time Limit Exceeded

Solution code:
def p_e():
    h, w = map(int, input().split())
    t = [list(map(int, input().split())) for _ in range(h)]
    m = 0
    for i in range(h):
        *b, = map(int, input().split())
        for j, e in enumerate(b):
            t[i][j] = abs(t[i][j] - e)
            if m < abs(t[i][j] - e):
                m = abs(t[i][j] - e)

    # dp[i][j][k]: (i,j)でkになるかどうかbool値
    bool_width = m * (h + w - 1)
    dp = [[[False] * bool_width for _ in range(w)] for _ in range(h)]
    for i in range(h):
        for j in range(w):
            if i == j == 0:
                dp[i][j][t[i][j]] = True
                continue
            for k in range(bool_width):
                if i > 0:
                    if abs(k + t[i][j]) < bool_width:
                        dp[i][j][k] |= dp[i - 1][j][abs(k + t[i][j])]
                    if abs(k - t[i][j]) < bool_width:
                        dp[i][j][k] |= dp[i - 1][j][abs(k - t[i][j])]
                if j > 0:
                    if abs(k + t[i][j]) < bool_width:
                        dp[i][j][k] |= dp[i][j - 1][abs(k + t[i][j])]
                    if abs(k - t[i][j]) < bool_width:
                        dp[i][j][k] |= dp[i][j - 1][abs(k - t[i][j])]
    for i, e in enumerate(dp[-1][-1]):
        if e:
            print(i)
            break
            
p_e()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
h,w=map(int,input().split())
a=[]
for i in range(h):
    a.append(list(map(int,input().split())))
b=[]
for i in range(h):
    b.append(list(map(int,input().split())))
dp=[[set([]) for i in range(w)] for j 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):
        if i==j==0:
            continue
        if i==0:
            for k in dp[i][j-1]:
                dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        elif j==0:
            for k in dp[i-1][j]:
                dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        else:
            for k in (dp[i][j-1]|dp[i-1][j]):
                if k<=6400:
                    dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                    dp[i][j].add(abs(k+b[i][j]-a[i][j]))             
#dp[h-1][w-1]
ans=10**10
for i in dp[h-1][w-1]:
    ans=min(ans,abs(i))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
import bisect
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop


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


def I(): return int(sys.stdin.readline())


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


# A
def A():
    a, b, c = LI()
    if a + b + c >= 22:
        print("bust")
    else:
        print("win")
    return


# B
def B():
    s = S()
    ans = 0
    for i in range(len(s) // 2):
        if s[i] != s[-i - 1]:
            ans += 1
    print(ans)
    return


# C
def C():
    n = I()
    res = [[0] * n for i in range(n)]
    ans = 0
    for i in range(n):
        a = I()
        for j in range(a):
            x, y = LI()
            if y == 0:
                res[i][x - 1] = 1
    while (1):
        max_num = 0
        max_ind = -1
        for i in range(n):
            num = 0
            for j in range(n):
                if i == j:
                    num += sum(res[i])
                else:
                    if res[j][i] == 1:
                        num += 1
            if num > max_num:
                max_num = num
                max_ind = i
        if max_ind == -1:
            print(n - ans)
            return
        else:
            ans += 1
            res[max_ind] = [0] * n
            for i in range(n):
                res[i][max_ind] = 0
    return


# D
def D():
    return


# E
def E():
    h, w = LI()
    a = [LI() for i in range(h)]
    b = [LI() for i in range(h)]
    max_num = 0
    for i in range(h):
        for j in range(w):
            max_num = max(max_num, abs(a[i][j] - b[i][j]))
    max_num = max_num * (h + w) + 1
    dp = [[[0] * max_num for i in range(w)] for i in range(h)]
    dp[0][0][abs(a[0][0] - b[0][0])] = 1
    for i in range(1, h):
        for num in range(max_num):
            if dp[i - 1][0][num] == 1:
                dp[i][0][abs(num + abs(a[i][0] - b[i][0]))] = 1
                dp[i][0][abs(num - abs(a[i][0] - b[i][0]))] = 1
    for i in range(1, w):
        for num in range(max_num):
            if dp[0][i - 1][num] == 1:
                dp[0][i][abs(num + abs(a[0][i] - b[0][i]))] = 1
                dp[0][i][abs(num - abs(a[0][i] - b[0][i]))] = 1
    for i in range(1, h):
        for j in range(1, w):
            for num in range(max_num):
                if dp[i - 1][j][num] == 1:
                    dp[i][j][abs(num + abs(a[i][j] - b[i][j]))] = 1
                    dp[i][j][abs(num - abs(a[i][j] - b[i][j]))] = 1
                if dp[i][j - 1][num] == 1:
                    dp[i][j][abs(num + abs(a[i][j] - b[i][j]))] = 1
                    dp[i][j][abs(num - abs(a[i][j] - b[i][j]))] = 1
    for i in range(100):
        if dp[h - 1][w - 1][i] == 1:
            print(i)
            break
    return


# F
def F():
    return


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

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
h,w=map(int,input().split())
a=[]
for i in range(h):
    a.append(list(map(int,input().split())))
b=[]
for i in range(h):
    b.append(list(map(int,input().split())))
dp=[[set([]) for i in range(w)] for j 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):
        if i==j==0:
            continue
        if i==0:
            for k in dp[i][j-1]:
                dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        elif j==0:
            for k in dp[i-1][j]:
                dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        else:
            for k in (dp[i][j-1]|dp[i-1][j]):
                if k<=6490:
                    dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                    dp[i][j].add(abs(k+b[i][j]-a[i][j]))             
#dp[h-1][w-1]
ans=10**10
for i in dp[h-1][w-1]:
    ans=min(ans,abs(i))
print(ans)

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=int)
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()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline 
readlines = sys.stdin.readlines

#n = int(input())
h,w = [int(i) for i in readline().split()]

a = [[int(i) for i in readline().split()] for _ in range(h)]
b = [[int(i) for i in readline().split()] for _ in range(h)]


dp = [set() for _ in range(w)]
dp[0] = set([0])

#print(dp)
for i in range(h):
    ndp = [set() for _ in range(w)]
    for j in range(w):
        v = abs(a[i][j] - b[i][j])
        #print(v)
        s1 = set(c+v for c in dp[j] if c+v <= 6400)
        s2 = set(abs(c-v) for c in dp[j] if c >= v)
        if j:
            s3 = set(c+v for c in ndp[j-1] if c+v <= 6400)
            s4 = set(abs(c-v) for c in ndp[j-1])
            ndp[j] = s1|s2|s3|s4
        else:
            ndp[j] = s1|s2
            
    dp = ndp
    #print(dp)
    

print(min(dp[j]))

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=[[[0]*M for i in range(w)] for j in range(h)]

	
	li[0][0][G[0][0]]=1
	for i in range(h):
		for j in range(w):
			for k in range(M):

				if li[i][j][k]==1:
					if i<h-1:
						li[i + 1][j][abs(k - G[i][j])] = 1
						li[i + 1][j][abs(k + G[i][j])] = 1
					if j<w-1:
						li[i][j + 1][abs(k - G[i][j])] = 1
						li[i][j + 1][abs(k + G[i][j])] = 1

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
H, W = map(int,input().split())

A = np.array([input().split() for _ in range(H)], dtype=int)
B = np.array([input().split() for _ in range(H)], dtype=int)
C = np.abs(A-B)

dp = [[0 for _ in range(W)] for _ in range(H)]
# np.zeros((H,W,1000), dtype=bool) # マス(i,j)までの経路の偏りのとり得る値

dp[0][0] = C[0,0:1]

for h in range(H):
  for w in range(W):
    if h==0 and w==0: continue
    idx = np.zeros(0, dtype=int)
    if h > 0: idx = np.r_[idx, dp[h-1][w]]
    if w > 0: idx = np.r_[idx, dp[h][w-1]]
    idx = np.r_[idx + C[h,w], idx - C[h,w]]
    idx = np.abs(idx)
    idx = np.unique(idx)
    dp[h][w] = idx

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

Submission status: Time Limit Exceeded

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

    xss = [[int(x) for x in input().split()] for _ in range(h)]
    yss = [[int(y) for y in input().split()] for _ in range(h)]
    uss = [[x - y for x, y in zip(xs, ys)] for xs, ys in zip(xss, yss)]

    dp = [[set() for _ in range(w)] for __ in range(h)]

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

    for i in range(1, w):
        x = dp[0][i]
        for d in dp[0][i-1]:
            x.add(d + uss[0][i])
            x.add(d - uss[0][i])
    for i in range(1, h):
        x = dp[i][0]
        for d in dp[i-1][0]:
            x.add(d + uss[i][0])
            x.add(d - uss[i][0])
    
    for i in range(1, h):
        for j in range(1, w):
            x = dp[i][j]
            for d in dp[i-1][j]:
                x.add(d + uss[i][j])
                x.add(d - uss[i][j])
            for d in dp[i][j-1]:
                x.add(d + uss[i][j])
                x.add(d - uss[i][j])
    ans = min(abs(d) for d in dp[-1][-1])
    print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]
h,w=map(int,input().split())
a=[list(map(int,input().split())) for i in range(h)]
b=[list(map(int,input().split())) for i in range(h)]
d=[[0 for i in range(w)] for j in range(h)]
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*80)] 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*80):
            if dp[i][j][dis]:
                if i+1<h:
                    dp[i+1][j][abs(dis-d[i+1][j])]=True
                    if dis+d[i+1][j]<80*80:
                        dp[i+1][j][dis+d[i+1][j]]=True
                if j+1<w:
                    dp[i][j+1][abs(dis-d[i][j+1])]=True
                    if dis+d[i][j+1]<80*80:
                        dp[i][j+1][dis+d[i][j+1]]=True
for dis in range(80*80):
    if dp[-1][-1][dis]:
        print(dis)
        break

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
INF=10**18
def input():
    return sys.stdin.readline().rstrip()

def main():
    H,W=map(int,input().split())
    A=[[] for _ in range(H)]
    B=[[] for _ in range(H)]
    C=[[0]*W for _ in range(H)]
    for i in range(H):
        A[i]=list(map(int,input().split()))
    for i in range(H):
        B[i]=list(map(int,input().split()))
    for i in range(H):
        for j in range(W):
            C[i][j]=abs(A[i][j]-B[i][j])
    dp=[[[False]*((H+W)*80*2+1) for _ in range(W)] for _ in range(H)]
    dp[0][0][C[0][0]]=True
    dp[0][0][-C[0][0]]=True
    for i in range(1,H):
        for k in range((H+W)*80*2+1):
            if dp[i-1][0][k]==True:
                dp[i][0][(k+C[i][0])%((H+W)*80*2+1)]=True
                dp[i][0][k-C[i][0]]=True
    for j in range(1,W):
        for k in range((H+W)*80*2+1):
            if dp[0][j-1][k]==True:
                dp[0][j][(k+C[0][j])%((H+W)*80*2+1)]=True
                dp[0][j][k-C[0][j]]=True
    
    for i in range(1,H):
        for j in range(1,W):
            for k in range((H+W)*80*2+1):
                if dp[i-1][j][k]==True:
                    dp[i][j][(k+C[i][j])%((H+W)*80*2+1)]=True
                    dp[i][j][k-C[i][j]]=True
                if dp[i][j-1][k]==True:
                    dp[i][j][(k+C[i][j])%((H+W)*80*2+1)]=True
                    dp[i][j][k-C[i][j]]=True
    for i in range((H+W)*80+1):
        if dp[H-1][W-1][i]==True:
            print(i)
            exit()
    pass
    
    

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

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=[[[0]*M for i in range(w)] for j in range(h)]

	
	li[0][0][G[0][0]]=1
	for i in range(h):
		for j in range(w):
			for k in range(M):

				if li[i][j][k]==1:

					try:
						li[i + 1][j][abs(k - G[i][j])] = 1
						li[i + 1][j][abs(k + G[i][j])] = 1
					except:
						pass
					try:
						li[i][j + 1][abs(k - G[i][j])] = 1
						li[i][j + 1][abs(k + G[i][j])] = 1
					except:
						pass
	
	for i in range(M):
		if li[h-1][w-1][i]==1:
			print(i-1)
			exit(0)
	
if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

import sys

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

def build_grid(H, W, intv, _type, space=True, padding=False):
    # 入力がスペース区切りかどうか
    if space:
        _input = lambda: input().split()
    else:
        _input = lambda: input()
    _list = lambda: list(map(_type, _input()))
    # 余白の有無
    if padding:
        offset = 1
    else:
        offset = 0
    grid = list2d(H+offset*2, W+offset*2, intv)
    for i in range(offset, H+offset):
        row = _list()
        for j in range(offset, W+offset):
            grid[i][j] = row[j-offset]
    return grid

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

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

dp = list3d(H+1, W+1, MAXV+1, 0)
dp[0][0][0] = 1
for i in range(H):
    for j in range(W):
        v = grid[i][j]
        for k in range(MAXV+1):
            if (i+j+1) * 80 < k:
                break
            dp[i+1][j][abs(k-v)] |= dp[i][j][k]
            if k+v <= MAXV:
                dp[i+1][j][k+v] |= dp[i][j][k]
            dp[i][j+1][abs(k-v)] |= dp[i][j][k]
            if k+v <= MAXV:
                dp[i][j+1][k+v] |= dp[i][j][k]
ans = INF
for k in range(MAXV+1):
    if dp[H][W-1][k]:
        ans = min(ans, k)
    if dp[H-1][W][k]:
        ans = min(ans, k)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]
h,w=map(int,input().split())
a=[list(map(int,input().split())) for i in range(h)]
b=[list(map(int,input().split())) for i in range(h)]
d=[[0 for i in range(w)] for j in range(h)]
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

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=[[[10**9]*M for i in range(w)] for j in range(h)]

	
	li[0][0][G[0][0]]=G[0][0]
	for i in range(h):
		for j in range(w):
			for k in range(M):

				if li[i][j][k]!=10**9:

					try:
						li[i + 1][j][abs(k - G[i][j])] = abs(k - G[i][j])
						li[i + 1][j][abs(k + G[i][j])] = abs(k + G[i][j])
					except:
						pass
					try:
						li[i][j + 1][abs(k - G[i][j])] = abs(k - G[i][j])
						li[i][j + 1][abs(k + G[i][j])] = abs(k + G[i][j])
					except:
						pass
	
	
	print(min(li[h-1][w-1])-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
    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]:
                if d+g <= M:
                    state[h][w].add(d+g)
                state[h][w].add(abs(d-g))
        if w-1 >= 0:
            for d in state[h][w-1]:
                if d+g <= M:
                    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:
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 = [[set() 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].add(C[i][j])
            else:
                for x in dp[i][j-1]:
                    dp[i][j].add(abs(x-C[i][j]))
                    dp[i][j].add(x+C[i][j])

        else:
            if j != 0:
                for x in dp[i][j-1]:
                    dp[i][j].add(abs(x-C[i][j]))
                    dp[i][j].add(x+C[i][j])

            for x in dp[i-1][j]:
                dp[i][j].add(abs(x-C[i][j]))
                dp[i][j].add(x+C[i][j])

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
import bisect
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop


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


def I(): return int(sys.stdin.readline())


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


# A
def A():
    a, b, c = LI()
    if a + b + c >= 22:
        print("bust")
    else:
        print("win")
    return


# B
def B():
    s = S()
    ans = 0
    for i in range(len(s) // 2):
        if s[i] != s[-i - 1]:
            ans += 1
    print(ans)
    return


# C
def C():
    n = I()
    res = [[0] * n for i in range(n)]
    ans = 0
    for i in range(n):
        a = I()
        for j in range(a):
            x, y = LI()
            if y == 0:
                res[i][x - 1] = 1
    while (1):
        max_num = 0
        max_ind = -1
        for i in range(n):
            num = 0
            for j in range(n):
                if i == j:
                    num += sum(res[i])
                else:
                    if res[j][i] == 1:
                        num += 1
            if num > max_num:
                max_num = num
                max_ind = i
        if max_ind == -1:
            print(n - ans)
            return
        else:
            ans += 1
            res[max_ind] = [0] * n
            for i in range(n):
                res[i][max_ind] = 0
    return


# D
def D():
    return


# E
def E():
    h, w = LI()
    a = [LI() for i in range(h)]
    b = [LI() for i in range(h)]
    max_num = 80 ** 2 * 2 + 10
    dp = [[[0] * max_num for i in range(w)] for i in range(h)]
    dp[0][0][abs(a[0][0] - b[0][0])] = 1
    for i in range(1, h):
        for num in range(max_num):
            if dp[i - 1][0][num] == 1:
                dp[i][0][abs(num + abs(a[i][0] - b[i][0]))] = 1
                dp[i][0][abs(num - abs(a[i][0] - b[i][0]))] = 1
    for i in range(1, w):
        for num in range(max_num):
            if dp[0][i - 1][num] == 1:
                dp[0][i][abs(num + abs(a[0][i] - b[0][i]))] = 1
                dp[0][i][abs(num - abs(a[0][i] - b[0][i]))] = 1
    for i in range(1, h):
        for j in range(1, w):
            for num in range(max_num):
                if dp[i - 1][j][num] == 1:
                    dp[i][j][abs(num + abs(a[i][j] - b[i][j]))] = 1
                    dp[i][j][abs(num - abs(a[i][j] - b[i][j]))] = 1
                if dp[i][j - 1][num] == 1:
                    dp[i][j][abs(num + abs(a[i][j] - b[i][j]))] = 1
                    dp[i][j][abs(num - abs(a[i][j] - b[i][j]))] = 1
    for i in range(100):
        if dp[h - 1][w - 1][i] == 1:
            print(i)
            break
    return


# F
def F():
    return


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