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:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#solve
def solve():
    h, w = LI()
    a = LIR(h)
    b = LIR(h)
    ab = abs(a[0][0] - b[0][0])
    d = defaultdict(set)
    d[(0, 0)].add(ab)
    for _ in range(h + w - 2):
        nd = defaultdict(set)
        for key, value in d.items():
            x, y = key
            if 0 <= x + 1 < w:
                x1y = abs(a[y][x + 1] - b[y][x + 1])
                for v in value:
                    nd[(x+1, y)].add(abs(v - x1y))
                    nd[(x+1, y)].add(v + x1y)
            if 0 <= y + 1 < h:
                xy1 = abs(a[y + 1][x] - b[y + 1][x])
                for v in value:
                    nd[(x, y+1)].add(abs(v - xy1))
                    nd[(x, y+1)].add(v + xy1)
        d = nd
    print(min(d[(w-1,h-1)]))
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
sa=[]
aa=[]
bb=[]
h,w=map(int,input().split())
for i in range(h):
	a=list(map(int,input().split()))
	aa.append(a)
for i in range(h):
	b=list(map(int,input().split()))
	bb.append(b)
MM=0
for i in range(h):
	ttt=[]
	for j in range(w):
		MM=max(MM,abs(aa[i][j]-bb[i][j]))
		ttt.append(abs(aa[i][j]-bb[i][j]))
	sa.append(ttt)
dp=[[[] for _ in range(w)]for _ in range(h)]
dp[0][0].append(sa[0][0])
for i in range(h-1):
	for j in range(len(dp[i][0])):
		if dp[i][0][j]+sa[i+1][0]<=(i+1)*MM:
			dp[i+1][0].append(dp[i][0][j]+sa[i+1][0])
		if abs(dp[i][0][j]-sa[i+1][0])<=(i+1)*MM:
			dp[i+1][0].append(abs(dp[i][0][j]-sa[i+1][0]))
		dp[i+1][0]=set(dp[i+1][0])
		dp[i+1][0]=list(dp[i+1][0])
for i in range(w-1):
	for j in range(len(dp[0][i])):
		if dp[0][i][j]+sa[0][i+1]<=(i+1)*MM:
			dp[0][i+1].append(dp[0][i][j]+sa[0][i+1])
		if abs(dp[0][i][j]-sa[0][i+1])<=(i+1)*MM:
			dp[0][i+1].append(abs(dp[0][i][j]-sa[0][i+1]))
		dp[0][i+1]=set(dp[0][i+1])
		dp[0][i+1]=list(dp[0][i+1])
for i in range(h-1):
	for k in range(w-1):
		for j in range(len(dp[i][k+1])):
			if dp[i][k+1][j]+sa[i+1][k+1]<=(i+1)*(k+1)*MM:
				dp[i+1][k+1].append(dp[i][k+1][j]+sa[i+1][k+1])
			if abs(dp[i][k+1][j]-sa[i+1][k+1])<=(i+1)*(k+1)*MM:
				dp[i+1][k+1].append(abs(dp[i][k+1][j]-sa[i+1][k+1]))
		for j in range(len(dp[i+1][k])):
			if dp[i+1][k][j]+sa[i+1][k+1]<=(i+1)*(k+1)*MM:
				dp[i+1][k+1].append(dp[i+1][k][j]+sa[i+1][k+1])
			if abs(dp[i+1][k][j]-sa[i+1][k+1])<=(i+1)*(k+1)*MM:
				dp[i+1][k+1].append(abs(dp[i+1][k][j]-sa[i+1][k+1]))
		dp[i+1][k+1]=set(dp[i+1][k+1])
		dp[i+1][k+1]=list(dp[i+1][k+1])
print(min(dp[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
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 = [[[0] * ((H+W)*80) for _ in range(W)] for _ in range(H)]
dp[0][0][abs(A[0][0]-B[0][0])] = 1

for i in range(H):
    for j in range(W):
        dif = abs(A[i][j] - B[i][j])
        if i > 0:
            for k in range((H+W)*80):
                if dp[i-1][j][k] == 1:
                    dp[i][j][k+dif] = 1
                    if k >= dif:
                        dp[i][j][k-dif] = 1
                    else:
                        dp[i][j][dif-k] = 1
        if j > 0:
            for k in range((H+W)*80):
                if dp[i][j-1][k] == 1:
                    dp[i][j][k+dif] = 1
                    if k >= dif:
                        dp[i][j][k-dif] = 1
                    else:
                        dp[i][j][dif-k] = 1

for k in range(H*W*80):
    if dp[H-1][W-1][k] == 1:
        ans = k
        break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
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 = [[[0] * (H*W*80) for _ in range(W)] for _ in range(H)]
dp[0][0][abs(A[0][0]-B[0][0])] = 1

for i in range(H):
    for j in range(W):
        dif = abs(A[i][j] - B[i][j])
        if i > 0:
            for k in range(H*W*80):
                if dp[i-1][j][k] == 1:
                    dp[i][j][k+dif] = 1
                    if k >= dif:
                        dp[i][j][k-dif] = 1
                    else:
                        dp[i][j][dif-k] = 1
        if j > 0:
            for k in range(H*W*80):
                if dp[i][j-1][k] == 1:
                    dp[i][j][k+dif] = 1
                    if k >= dif:
                        dp[i][j][k-dif] = 1
                    else:
                        dp[i][j][dif-k] = 1

for k in range(H*W*80):
    if dp[H-1][W-1][k] == 1:
        ans = k
        break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
sa=[]
aa=[]
bb=[]
h,w=map(int,input().split())
for i in range(h):
	a=list(map(int,input().split()))
	aa.append(a)
for i in range(h):
	b=list(map(int,input().split()))
	bb.append(b)
for i in range(h):
	ttt=[]
	for j in range(w):
		ttt.append(abs(aa[i][j]-bb[i][j]))
	sa.append(ttt)
dp=[[[] for _ in range(w)]for _ in range(h)]
dp[0][0].append(sa[0][0])
for i in range(h-1):
	for j in range(len(dp[i][0])):
		if dp[i][0][j]+sa[i+1][0]<=h*w*80:
			dp[i+1][0].append(dp[i][0][j]+sa[i+1][0])
		if abs(dp[i][0][j]-sa[i+1][0])<=h*w*80:
			dp[i+1][0].append(abs(dp[i][0][j]-sa[i+1][0]))
		dp[i+1][0]=set(dp[i+1][0])
		dp[i+1][0]=list(dp[i+1][0])
for i in range(w-1):
	for j in range(len(dp[0][i])):
		if dp[0][i][j]+sa[0][i+1]<=h*w*80:
			dp[0][i+1].append(dp[0][i][j]+sa[0][i+1])
		if abs(dp[0][i][j]-sa[0][i+1])<=h*w*80:
			dp[0][i+1].append(abs(dp[0][i][j]-sa[0][i+1]))
		dp[0][i+1]=set(dp[0][i+1])
		dp[0][i+1]=list(dp[0][i+1])
for i in range(h-1):
	for k in range(w-1):
		for j in range(len(dp[i][k+1])):
			if dp[i][k+1][j]+sa[i+1][k+1]<=h*w*80:
				dp[i+1][k+1].append(dp[i][k+1][j]+sa[i+1][k+1])
			if abs(dp[i][k+1][j]-sa[i+1][k+1])<=h*w*80:
				dp[i+1][k+1].append(abs(dp[i][k+1][j]-sa[i+1][k+1]))
		for j in range(len(dp[i+1][k])):
			if dp[i+1][k][j]+sa[i+1][k+1]<=h*w*80:
				dp[i+1][k+1].append(dp[i+1][k][j]+sa[i+1][k+1])
			if abs(dp[i+1][k][j]-sa[i+1][k+1])<=h*w*80:
				dp[i+1][k+1].append(abs(dp[i+1][k][j]-sa[i+1][k+1]))
		dp[i+1][k+1]=set(dp[i+1][k+1])
		dp[i+1][k+1]=list(dp[i+1][k+1])
print(min(dp[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

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

ma = 90*90
DP = [[[0]*(2*ma) for j in range(w+1)] for i in range(h+1)]
mid = ma
DP[0][0][mid] = 1

for i in range(h):
    for j in range(w):
        k = abs(a[i][j]-b[i][j])
        for l in range(2*ma):
            if not DP[i][j][l]:
                continue
            if 0<=l-k:
                DP[i+1][j][l-k] = 1
                DP[i][j+1][l-k] = 1
            if l+k<2*ma:
                DP[i+1][j][l+k] = 1
                DP[i][j+1][l+k] = 1

ans = float("Inf")
for i, j in [(h,w-1),(h-1,w)]:
    for k in range(2*ma):
        if DP[i][j][k]:
            ans = min(ans, abs(mid-k))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict
input = sys.stdin.readline
H, W = map(int, input().split())
A, B = [None] * H, [None] * 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()))
C = [[abs(A[i][j] - B[i][j]) for j in range(W)] for i in range(H)]
M = 80*(80+80)
dp = [[defaultdict(lambda :False) for j in range(W+1)] for i in range(H+1)]
dp[0][1][0] = True
dp[1][0][0] = True
for i in range(1, H+1):
    for j in range(1, W+1):
        d = C[i-1][j-1]
        for k in range((i+j-1)*80):
            if dp[i-1][j][abs(k-d)] or dp[i-1][j][k+d] or dp[i][j-1][abs(k-d)] or dp[i][j-1][k+d]:
                dp[i][j][k] = True

for i in range(M):
    if i in dp[H][W]:
        print(i)
        break

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H, W = map(int, input().split())
A, B = [None] * H, [None] * 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()))
C = [[abs(A[i][j] - B[i][j]) for j in range(W)] for i in range(H)]
M = 80*(80+80)
dp = [[[False for _ in range(M)] for j in range(W)] for i in range(H)]
dp[0][0][C[0][0]] = True
for i in range(H):
    for j in range(W):
        D = i + j
        d = C[i][j]
        for k in range((i+j+1)*80):
            if i != 0:
                if dp[i-1][j][abs(k-d)]:
                    dp[i][j][k] = True
                elif dp[i-1][j][k+d]:
                    dp[i][j][k] = True
            if j != 0:
                if dp[i][j-1][abs(k-d)]:
                    dp[i][j][k] = True
                elif dp[i][j-1][k+d]:
                    dp[i][j][k] = True

for i, v in enumerate(dp[H-1][W-1]):
    if v:
        print(i)
        break

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H, W = map(int, input().split())
A, B = [None] * H, [None] * 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()))
C = [[abs(A[i][j] - B[i][j]) for j in range(W)] for i in range(H)]
M = 80*(80+80)
#M = 100
dp = [[[False for _ in range(M)] for j in range(W)] for i in range(H)]
dp[0][0][C[0][0]] = True
for i in range(H):
    for j in range(W):
        d = C[i][j]
        for k in range(M-80):
            if i != 0:
                if dp[i-1][j][abs(k-d)]:
                    dp[i][j][k] = True
                elif dp[i-1][j][k+d]:
                    dp[i][j][k] = True
            if j != 0:
                if dp[i][j-1][abs(k-d)]:
                    dp[i][j][k] = True
                elif dp[i][j-1][k+d]:
                    dp[i][j][k] = True

for i, v in enumerate(dp[H-1][W-1]):
    if v:
        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)]

c = [[0 for _ in range(w)] for _ in range(h)]

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

z = 80 * (h+w) + 1
dp = [[[0 for _ in range(z)] for _ in range(w)] for _ in range(h)]
dp[0][0][c[0][0]] = 1

for i in range(h+w-1):
    for x in range(min(i+1, h)):
        y = i - x
        if y >= w:
            continue
        for j in range(z):
            if dp[x][y][j] == 1:
                if x < h-1:
                    dp[x + 1][y][j + c[x + 1][y]] = 1
                    dp[x + 1][y][abs(j - c[x + 1][y])] = 1
                if y < w-1:
                    dp[x][y + 1][j + c[x][y + 1]] = 1
                    dp[x][y + 1][abs(j - c[x][y + 1])] = 1

#print(dp[h-1][w-1])

for i in range(z):
    if dp[h-1][w-1][i] == 1:
        print(i)
        exit()

Submission status: Time Limit Exceeded

Solution code:
from sys import stdout
from collections import defaultdict
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 = 12801
K = 6400
h,w = inm()
dp = [[defaultdict(int) 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]] = 1
dp[0][0][-a[0][0]+b[0][0]] = 1

for i in range(0,h):
  for j in range(0,w):
    if j>0:
      for u in dp[i][j-1]:
        x = u + a[i][j] - b[i][j]
        y = u - a[i][j] + b[i][j]
        dp[i][j][x]==1
        dp[i][j][y]==1
    if i>0:
      for u in dp[i-1][j]:
        x = u + a[i][j] - b[i][j]
        y = u - a[i][j] + b[i][j]
        dp[i][j][x]==1
        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 dp[h-1][w-1]:
    if abs(u)<mn:
        mn = abs(u)
print(mn)

Submission status: Time Limit Exceeded

Solution code:
# problem E

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())))
D=[[abs(A[i][j]-B[i][j]) for j in range(W)] for i in range(H)]

dp=[[set() for j in range(W)] for i in range(H)]
dp[0][0].add(D[0][0])

for j in range(1,W):
    for d in dp[0][j-1]:
        dp[0][j].update({d+D[0][j],abs(d-D[0][j])})

for i in range(1,H):
    for d in dp[i-1][0]:
        dp[i][0].update({d+D[i][0],abs(d-D[i][0])})

for i in range(1,H):
    for j in range(1,W):
        for d in dp[i-1][j]:
            dp[i][j].update({d+D[i][j],abs(d-D[i][j])})
        for d in dp[i][j-1]:
            dp[i][j].update({d+D[i][j],abs(d-D[i][j])})

ans=min(dp[H-1][W-1])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# problem E

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())))
D=[[abs(A[i][j]-B[i][j]) for j in range(W)] for i in range(H)]

dp=[[[False for d in range((H+W)*80+1)] for j in range(W)] for i in range(H)]
dp[0][0][D[0][0]]=True

for j in range(1,W):
    for d in range((H+W)*80+1):
        if dp[0][j-1][d]:
            dp[0][j][d+D[0][j]]=True
            dp[0][j][abs(d-D[0][j])]=True

for i in range(1,H):
    for d in range((H+W)*80+1):
        if dp[i-1][0][d]:
            dp[i][0][d+D[i][0]]=True
            dp[i][0][abs(d-D[i][0])]=True

for i in range(1,H):
    for j in range(1,W):
        for d in range((H+W)*80+1):
            if dp[i-1][j][d]:
                dp[i][j][d+D[i][j]]=True
                dp[i][j][abs(d-D[i][j])]=True
            if dp[i][j-1][d]:
                dp[i][j][d+D[i][j]]=True
                dp[i][j][abs(d-D[i][j])]=True

ans=min([d for d in range((H+W)*80+1) if dp[H-1][W-1][d]])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int, input().split( ))
a = []
b = []
for i in range(h):
    ai = list(map(int, input().split( )))
    a.append(ai)
for i in range(h):
    bi = list(map(int, input().split( )))
    for j in range(w):
        a[i][j]-=bi[j]
        a[i][j] = abs(a[i][j])
###差のmaxまでをlistで確保する代わりに可能な値をsetで保持
dp = [[set() for j in range(w)] for i in range(h)]
dp[0][0].add(a[0][0])

for j in range(1,w):
    for k in dp[0][j-1]:
        dp[0][j].add(abs(k-a[0][j]))
        dp[0][j].add(k+a[0][j])

for i in range(1,h):
    for j in range(w):
        for k in dp[i-1][j]:
            dp[i][j].add(abs(k-a[i][j]))
            dp[i][j].add(k+a[i][j])
        if j:
            for k in dp[i][j-1]:
                dp[i][j].add(abs(k-a[i][j]))
                dp[i][j].add(k+a[i][j])
#print(dp)
ans = 10**10
for k in dp[h-1][w-1]:
    ans = min(ans,k)
        
print(ans)

Submission status: Time Limit Exceeded

Solution code:
e=enumerate
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=[[]for _ in range(w)]
for i,(a,b)in e(zip(a,b)):
  for j,(x,y)in e(zip(a,b)):
    x-=y
    t=set()
    add=t.add
    if j:
      for v in dp[j-1]:
        add(v+x)
        add(v-x)
    if i:
      for v in dp[j]:
        add(v+x)
        add(v-x)
    if i+j:dp[j]=t
    else:dp[j]={x}
print(min(map(abs,dp[w-1])))

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int, input().split( ))
a = []
b = []
for i in range(h):
    ai = list(map(int, input().split( )))
    a.append(ai)
for i in range(h):
    bi = list(map(int, input().split( )))
    for j in range(w):
        a[i][j]-=bi[j]
        a[i][j] = abs(a[i][j])

dp = [[[0]*16000 for j in range(w)] for i in range(h)]
dp[0][0][a[0][0]] = 1


for j in range(1,w):
    for k in range(13000):
        dp[0][j][k] += dp[0][j-1][abs(k-a[0][j])]##aのindexは-1不要
        dp[0][j][k] += dp[0][j-1][k+a[0][j]]

for i in range(1,h):
    for j in range(w):
        for k in range(13000):
            dp[i][j][k] += dp[i-1][j][abs(k-a[i][j])]
            dp[i][j][k] += dp[i-1][j][k+a[i][j]]
            if j:
                dp[i][j][k] += dp[i][j-1][abs(k-a[i][j])]
                dp[i][j][k] += dp[i][j-1][k+a[i][j]]
ans = -1
for k in range(13000):
    if dp[h-1][w-1][k]>0:
        ans = k
        break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
e=enumerate
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=[[]for _ in range(w)]
for i,(a,b)in e(zip(a,b)):
  for j,(x,y)in e(zip(a,b)):
    x,y=x-y,y-x
    t=set()
    add=t.add
    if j:
      for v in dp[j-1]:
        add(v+x)
        add(v+y)
    if i:
      for v in dp[j]:
        add(v+x)
        add(v+y)
    if i+j:dp[j]=t
    else:dp[j]={x,y}
print(min(map(abs,dp[w-1])))

Submission status: Time Limit Exceeded

Solution code:
e=enumerate
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}for _ in range(w)]
dp[0]={a[0][0]-b[0][0],b[0][0]-a[0][0]}
for i,(a,b)in e(zip(a,b)):
  for j,(x,y)in e(zip(a,b)):
    if i+j:
      x,y=x-y,y-x
      t=set()
      add=t.add
      if i:
        for v in dp[j]:
          add(v+x)
          add(v+y)
      if j:
        for v in dp[j-1]:
          add(v+x)
          add(v+y)
      dp[j]=t
print(min(map(abs,dp[w-1])))

Submission status: Time Limit Exceeded

Solution code:
e=enumerate
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=[[]for _ in range(w)]
dp[0]={a[0][0]-b[0][0],b[0][0]-a[0][0]}
for i,(a,b)in e(zip(a,b)):
  for j,(d,x,y)in e(zip(dp,a,b)):
    x,y=x-y,y-x
    t=set()
    add=t.add
    if i:
      for v in d:
        add(v+x)
        add(v+y)
    if j:
      for v in dp[j-1]:
        add(v+x)
        add(v+y)
    if i+j:dp[j]=t
print(min(map(abs,dp[w-1])))

Submission status: Time Limit Exceeded

Solution code:
e=enumerate
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=[[]for _ in range(w)]
dp[0]={a[0][0]-b[0][0],b[0][0]-a[0][0]}
for i,(a,b)in e(zip(a,b)):
  for j,(d,x,y)in e(zip(dp,a,b)):
    x,y=x-y,y-x
    t=[]
    add=t.append
    if i:
      for v in d:
        add(v+x)
        add(v+y)
    if j:
      for v in dp[j-1]:
        add(v+x)
        add(v+y)
    if i+j:dp[j]=set(t)
print(min(map(abs,dp[w-1])))

Submission status: Time Limit Exceeded

Solution code:
e=enumerate
h,w,*t=map(int,open(0).read().split())
a=[t[i*w:(i+1)*w]for i in range(h)]
b=[t[i*w:(i+1)*w]for i in range(h,2*h)]
dp=[{0}for _ in range(w)]
dp[0]={a[0][0]-b[0][0],b[0][0]-a[0][0]}
for i,(a,b)in e(zip(a,b)):
  for j,(x,y)in e(zip(a,b)):
    x,y=x-y,y-x
    t=set()
    add=t.add
    if i:
      for v in dp[j]:
        add(v+x)
        add(v+y)
    if j:
      for v in dp[j-1]:
        add(v+x)
        add(v+y)
    if i+j:dp[j]=t
print(min(map(abs,dp[w-1])))

Submission status: Time Limit Exceeded

Solution code:
e=enumerate
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}for _ in range(w)]
dp[0]={a[0][0]-b[0][0],b[0][0]-a[0][0]}
for i,(a,b)in e(zip(a,b)):
  for j,(x,y)in e(zip(a,b)):
    x,y=x-y,y-x
    t=set()
    add=t.add
    if i:
      for v in dp[j]:
        add(v+x)
        add(v+y)
    if j:
      for v in dp[j-1]:
        add(v+x)
        add(v+y)
    if i+j:dp[j]=t
print(min(map(abs,dp[w-1])))

Submission status: Time Limit Exceeded

Solution code:
e=enumerate
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}for _ in range(w)]
dp[0]={a[0][0]-b[0][0],b[0][0]-a[0][0]}
for i,(a,b)in e(zip(a,b)):
  for j,(x,y)in e(zip(a,b)):
    t=set()
    add=t.add
    if i:
      for v in dp[j]:
        add(v+x-y)
        add(v-x+y)
    if j:
      for v in dp[j-1]:
        add(v+x-y)
        add(v-x+y)
    if i+j:dp[j]=t
print(min(map(abs,dp[w-1])))

Submission status: Time Limit Exceeded

Solution code:
e=enumerate
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}for _ in range(w)]
dp[0]={a[0][0]-b[0][0],b[0][0]-a[0][0]}
for i,(a,b)in e(zip(a,b)):
  for j,(x,y)in e(zip(a,b)):
    t=set()
    if i:
      for v in dp[j]:
        t|={v+x-y}
        t|={v-x+y}
    if j:
      for v in dp[j-1]:
        t|={v+x-y}
        t|={v-x+y}
    if i+j:dp[j]=t
print(min(map(abs,dp[w-1])))

Submission status: Time Limit Exceeded

Solution code:
e=enumerate
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}for _ in range(w)]
dp[0]={a[0][0]-b[0][0],b[0][0]-a[0][0]}
for i,(a,b)in e(zip(a,b)):
  for j,(x,y)in e(zip(a,b)):
    t=set()
    if i:
      t|=set(t+x-y for t in dp[j])
      t|=set(t-x+y for t in dp[j])
    if j:
      t|=set(t+x-y for t in dp[j-1])
      t|=set(t-x+y for t in dp[j-1])
    if i+j:dp[j]=t
print(min(map(abs,dp[w-1])))

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict
input = sys.stdin.readline

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

A = [tuple(map(int, input().split())) for _ in range(H)]
B = [tuple(map(int, input().split())) for _ in range(H)]
dp = [[defaultdict(lambda : False) for _ in range(W)] for _ in range(H)]
dp[0][0][0] = True

for h in range(H):
    for w in range(W):
        C = A[h][w] - B[h][w]
        for v, f in dp[h][w].items():
            if f:
                if h < H - 1:
                    dp[h + 1][w][v + C] = True
                    dp[h + 1][w][v - C] = True
                if w < W - 1:
                    dp[h][w + 1][v + C] = True
                    dp[h][w + 1][v - C] = True

ans = 10**10
C = A[H - 1][W - 1] - B[H - 1][W - 1]
for v, f in dp[H - 1][W - 1].items():
    if f:
        ans = min(ans, abs(v - C))
        ans = min(ans, abs(v + C))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
H, W = map(int, input().split())

A = [tuple(map(int, input().split())) for _ in range(H)]
B = [tuple(map(int, input().split())) for _ in range(H)]
dp = [[defaultdict(lambda : False) for _ in range(W)] for _ in range(H)]
dp[0][0][0] = True

for h in range(H):
    for w in range(W):
        C = A[h][w] - B[h][w]
        for v, f in dp[h][w].items():
            if f:
                if h < H - 1:
                    dp[h + 1][w][v + C] = True
                    dp[h + 1][w][v - C] = True
                if w < W - 1:
                    dp[h][w + 1][v + C] = True
                    dp[h][w + 1][v - C] = True

ans = 10**10
C = A[H - 1][W - 1] - B[H - 1][W - 1]
for v, f in dp[H - 1][W - 1].items():
    if f:
        ans = min(ans, abs(v - C))
        ans = min(ans, abs(v + C))
print(ans)

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 = 12801
K = 6400
h,w = inm()
dp = [[[0]*2 for d in range(M)] for j in range(w)]

def getdp(i,j,d):
    if i>=64:
        return (dp[j][d+K][1] >> (i-64)) & 1
    else:
        return (dp[j][d+K][0] >> i) & 1

def setdp(i,j,d):
    if i>=64:
        dp[j][d+K][1] |= 1<<(i-64)
    else:
        dp[j][d+K][0] |= 1<<i

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

setdp(0,0,a[0][0]-b[0][0])
setdp(0,0,-a[0][0]+b[0][0])

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

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(-K,K+1):
    if getdp(h-1,w-1,u)==1 and abs(u)<mn:
        mn = abs(u)
print(mn)

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 = 12801
K = 6400
h,w = inm()
dp = [[0]*M for j in range(w)]

def getdp(i,j,d):
    return (dp[j][d+K] >> i) & 1

def setdp(i,j,d):
    dp[j][d+K] |= 1<<i

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

setdp(0,0,a[0][0]-b[0][0])
setdp(0,0,-a[0][0]+b[0][0])

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

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(-K,K+1):
    if getdp(h-1,w-1,u)==1 and abs(u)<mn:
        mn = abs(u)
print(mn)

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

dp = [[0] * w for i in range(h)]
dp[0][0] = 1 << c[0][0]

for j in range(1, w):
  dp_str = bin(dp[0][j-1])[:1:-1]
  for num, flag in enumerate(dp_str):
    if flag == '1':
      dp[0][j] |= 1 << abs(c[0][j] - num)
      dp[0][j] |= 1 << c[0][j] + num
    
for i in range(1, h):
  dp_str = bin(dp[i-1][0])[:1:-1]
  for num, flag in enumerate(dp_str):
    if flag == '1':
      dp[i][0] |= 1 << abs(c[i][0] - num)
      dp[i][0] |= 1 << c[i][0] + num
    
for i in range(1, h):
  for j in range(1, w):
    dp_str = bin(dp[i][j-1])[:1:-1]
    for num, flag in enumerate(dp_str):
      if flag == '1':
        dp[i][j] |= 1 << abs(c[i][j] - num)
        dp[i][j] |= 1 << c[i][j] + num
    dp_str = bin(dp[i-1][j])[:1:-1]
    for num, flag in enumerate(dp_str):
      if flag == '1':
        dp[i][j] |= 1 << abs(c[i][j] - num)
        dp[i][j] |= 1 << c[i][j] + num
      
print(bin(dp[-1][-1])[::-1].index('1'))

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):
		r = 80 * (i+j+2)
		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

"""
dp = [[set([]) for j in range(W)] for i in range(H)]
dp[0][0].add(D[0][0])
for i in range(H):
	for j in range(W):
		for s in dp[i][j]:
			if j != W-1:
				d = D[i][j+1]
				dp[i][j+1].add(s+d)
				dp[i][j+1].add(abs(s-d))
			if i != H-1:
				d = D[i+1][j]
				dp[i+1][j].add(s+d)
				dp[i+1][j].add(abs(s-d))
h,w = H-1, W-1
print(min(dp[h][w]))

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):
		r = 80 * (i+j+2)
		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()