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:
def main():
    H, W = map(int, input().split())
    A = [list(map(int, input().split())) for _ in range(H)]
    B = [list(map(int, input().split())) for _ in range(H)]
    C = [[0] * W for _ in range(H)]
    for h in range(H):
        for w in range(W):
            C[h][w] = abs(A[h][w] - B[h][w])

    dp = [[[0] * (80 * 80) for _ in range(W)] for _ in range(H)]
    dh = [1,0]
    dw = [0,1]
    dp[0][0][C[0][0]] = 1
    for h in range(H):
        for w in range(W):
            for i in range(80*80):
                for j in range(2):
                    nh = h - dh[j]
                    nw = w - dw[j]
                    if 0 <= nh < H and 0 <= nw < W:
                        if abs(C[h][w] + i) < 6400:
                            dp[h][w][abs(C[h][w] + i)] |= dp[nh][nw][i]
                        if abs(C[h][w] - i) < 6400:
                            dp[h][w][abs(C[h][w] - i)] |= dp[nh][nw][i]
                    
    ans = float('inf')
    for i in range(80*80):
        if dp[H-1][W-1][i]:
            ans = min(i, ans)

    print(ans) 



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import heapq

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)]
AB = [[0 for j in range(W)] for i in range(H)]

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

dp = [ [[] for j in range(W)] for i in range(H)]
for i in range(H):
	for j in range(W):
		if i==0 and j==0:
			dp[0][0] = [[AB[0][0]]]
		else:
			work_i = []
			work_j = []
			if i > 0:
				work_i = [k + [AB[i][j]] for k in dp[i-1][j]]
			if j > 0:
				work_j = [k + [AB[i][j]] for k in dp[i][j-1]]
			dp[i][j] = work_i + work_j
ans = []
for k in dp[H-1][W-1]:
	k = list(map(lambda x: x*(-1), k))
	heapq.heapify(k)
	while len(k) > 1:
		max1 = heapq.heappop(k)*(-1)
		max2 = heapq.heappop(k)*(-1)
		heapq.heappush(k,abs(max1-max2)*(-1))
	ans.append(heapq.heappop(k)*(-1))
print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys

    H, W = map(int, sys.stdin.readline().split())
    A = [list(map(int, sys.stdin.readline().split())) for i in range(H)]
    B = [list(map(int, sys.stdin.readline().split())) for i in range(H)]
    X = [[0] * W for i in range(H)]
    for h in range(H):
        for w in range(W):
            X[h][w] = abs(A[h][w] - B[h][w])

    dp = {}
    dp[0] = set()
    dp[0].add(X[0][0])
    dp[0].add(-X[0][0])

    for h in range(H):
        for w in range(W):
            if h == 0 and w == 0:
                continue
            x = X[h][w]
            s = set()

            threshold = ((H - h) + (W - w)) * 79
            if W * h + w > W - 1:
                for d in dp[W * (h - 1) + w]:

                    if d + x <= threshold:
                        s.add(d + x)
                    if d - x >= -threshold:
                        s.add(d - x)

            if (W * h + w) % W != 0:
                for d in dp[W * h + w - 1]:
                    if d + x <= threshold:
                        s.add(d + x)
                    if d - x >= -threshold:
                        s.add(d - x)

            dp[W * h + w] = s

    ans = min([abs(s) for s in dp[W * H - 1]])
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys

    H, W = map(int, sys.stdin.readline().split())
    A = [list(map(int, sys.stdin.readline().split())) for i in range(H)]
    B = [list(map(int, sys.stdin.readline().split())) for i in range(H)]
    X = [[None] * W for i in range(H)]
    for h in range(H):
        for w in range(W):
            X[h][w] = abs(A[h][w] - B[h][w])

    dp = {}
    dp[0] = set()
    dp[0].add(X[0][0])
    dp[0].add(-X[0][0])

    for h in range(H):
        for w in range(W):
            if h == 0 and w == 0:
                continue
            x = X[h][w]
            s = set()

            threshold = ((H - h) + (W - w)) * 79
            if W * h + w > W - 1:
                for d in dp[W * (h - 1) + w]:
                    
                    if d + x <= threshold:
                        s.add(d + x)
                    if d - x >= -threshold:
                        s.add(d - x)

            if (W * h + w) % W != 0:
                for d in dp[W * h + w - 1]:
                    if d + x <= threshold:
                        s.add(d + x)
                    if d - x >= -threshold:
                        s.add(d - x)

            dp[W * h + w] = s

    ans = min([abs(s) for s in dp[W * H - 1]])
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys

    H, W = map(int, sys.stdin.readline().split())
    A = [list(map(int, sys.stdin.readline().split())) for i in range(H)]
    B = [list(map(int, sys.stdin.readline().split())) for i in range(H)]
    X = [[None] * W for i in range(H)]
    for h in range(H):
        for w in range(W):
            X[h][w] = abs(A[h][w] - B[h][w])

    dp = {}
    dp[0] = set()
    dp[0].add(X[0][0])
    dp[0].add(-X[0][0])

    for h in range(H):
        for w in range(W):
            if h == 0 and w == 0:
                continue
            x = X[h][w]
            s = set()

            if W * h + w > W - 1:
                for d in dp[W * (h - 1) + w]:
                    if d + x <= ((H - h) + (W - w)) * 79:
                        s.add(d + x)
                    if d - x >= -((H - h) + (W - w)) * 79:
                        s.add(d - x)

            if (W * h + w) % W != 0:
                for d in dp[W * h + w - 1]:
                    if d + x <= ((H - h) + (W - w)) * 79:
                        s.add(d + x)
                    if d - x >= -((H - h) + (W - w)) * 79:
                        s.add(d - x)

            dp[W * h + w] = s

    ans = min([abs(s) for s in dp[W * H - 1]])
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    from collections import defaultdict

    H, W = map(int, sys.stdin.readline().split())
    A = [list(map(int, sys.stdin.readline().split())) for i in range(H)]
    B = [list(map(int, sys.stdin.readline().split())) for i in range(H)]
    X = [[None] * W for i in range(H)]
    for h in range(H):
        for w in range(W):
            X[h][w] = abs(A[h][w] - B[h][w])

    dp = defaultdict(set)
    dp[(0, 0)].add(X[0][0])
    dp[(0, 0)].add(-X[0][0])

    for h in range(H):
        for w in range(W):
            if h == 0 and w == 0:
                continue
            x = X[h][w]
            s = set()
            if h > 0:
                for d in dp[(h - 1, w)]:
                    s.add(d + x)
                    s.add(d - x)

            if w > 0:
                for d in dp[(h, w - 1)]:
                    s.add(d + x)
                    s.add(d - x)

            dp[(h, w)] = s

    ans = min([abs(s) for s in dp[(H - 1, W - 1)]])
    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)]
AB = [[0 for j in range(W)] for i in range(H)]

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

dp = [ [[] for j in range(W)] for i in range(H)]
for i in range(H):
	for j in range(W):
		if i==0 and j==0:
			dp[0][0] = [[AB[0][0]]]
		else:
			work_i = []
			work_j = []
			if i > 0:
				work_i = [k + [AB[i][j]] for k in dp[i-1][j]]
			if j > 0:
				work_j = [k + [AB[i][j]] for k in dp[i][j-1]]
			dp[i][j] = work_i + work_j
ans = []
for k in dp[H-1][W-1]:
	k.sort()
	while len(k) > 1:
		k.sort()
		k = k[:-2] + [abs(k[-1] - k[-2])]
	ans.append(k[0])
print(min(ans))

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 j in range(W)] for i in range(H)]

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

dp = [[[0 for k in range(6400)] for j in range(W)] for i in range(H)]
dp[0][0][C[0][0]] = 1

for i in range(H):
    for j in range(W):
        for k in range(6400):
            if not dp[i][j][k]:
                continue
            ni,nj = i+1,j+1
            if ni < H:
                if k+C[ni][j]<6400:
                    dp[ni][j][k+C[ni][j]] = 1
                dp[ni][j][abs(k-C[ni][j])] = 1
            if nj < W:
                if k+C[i][nj]<6400:
                    dp[i][nj][k+C[i][nj]] = 1
                dp[i][nj][abs(k-C[i][nj])] = 1

for k in range(6400):
    if dp[-1][-1][k]:
        print(k)
        break

Submission status: Time Limit Exceeded

Solution code:
def examE():
    H, W = LI()
    A = [LI() for _ in range(H)]
    B = [LI() for _ in range(H)]
    Diff = [[0] * W for _ in range(H)]
    M = 0
    for i in range(H):
        for j in range(W):
            m = abs(A[i][j] - B[i][j])
            Diff[i][j] = m
            M += m
    dp = [[0] * (W + 1) for _ in range(H + 1)]
    dp[0][0] |= (1 << Diff[H-1][W-1])
    for i in range(H):
        for j in range(W):
            here = dp[i][j]
            s = Diff[i][j]
            ni = (here << s) | (here >> s)
            ex = 0
            #溢れる分
            for k in range(1, s + 1):
                if (here >> k) & 1:
                    ex |= (1 << (s - k))
            dp[i + 1][j] |= (ni | ex)
            dp[i][j + 1] |= (ni | ex)
#            print(s,ni,here,ex,dp[i+1][j])

    a = dp[H - 1][W - 1]
    ans = 0
    for k in range(M + 1):
        if (a >> k) & 1:
            ans = k
            break
    print(dp)
    print(ans)
    return

def examE2():
    H, W = LI()
    A = [LI() for _ in range(H)]
    B = [LI() for _ in range(H)]
    loop = 80*80+1
    dp = [[False]*(loop) for _ in range(H*W)]
    cur = abs(A[0][0] - B[0][0])
    dp[0][cur] = True
    for i in range(H):
        for j in range(W):
            for k in range(loop):
                if dp[i*W+j][k]:
                    if i<H-1:
                        cur = abs(A[i+1][j] - B[i+1][j])
                        dp[(i+1)*W +j][abs(k - cur)] = True
                        if k+cur<loop:
                            dp[(i + 1) * W + j][k + cur] = True
                    if j<W-1:
                        cur = abs(A[i][j+1] - B[i][j+1])
                        dp[i*W+(j+1)][abs(k-cur)] = True
                        if k+cur<loop:
                            dp[i * W + (j + 1)][k + cur] = True
    #print(dp[-1])
    ans = inf
    for i,f in enumerate(dp[H*W-1]):
        if f:
            ans = i
            break
    print(ans)
    return

import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    examE2()

Submission status: Time Limit Exceeded

Solution code:
def examE():
    H, W = LI()
    A = [LI() for _ in range(H)]
    B = [LI() for _ in range(H)]
    Diff = [[0] * W for _ in range(H)]
    M = 0
    for i in range(H):
        for j in range(W):
            m = abs(A[i][j] - B[i][j])
            Diff[i][j] = m
            M += m
    dp = [[0] * (W + 1) for _ in range(H + 1)]
    dp[0][0] |= (1 << Diff[H-1][W-1])
    for i in range(H):
        for j in range(W):
            here = dp[i][j]
            s = Diff[i][j]
            ni = (here << s) | (here >> s)
            ex = 0
            #溢れる分
            for k in range(1, s + 1):
                if (here >> k) & 1:
                    ex |= (1 << (s - k))
            dp[i + 1][j] |= (ni | ex)
            dp[i][j + 1] |= (ni | ex)
#            print(s,ni,here,ex,dp[i+1][j])

    a = dp[H - 1][W - 1]
    ans = 0
    for k in range(M + 1):
        if (a >> k) & 1:
            ans = k
            break
    print(dp)
    print(ans)
    return

def examE2():
    H, W = LI()
    A = [LI() for _ in range(H)]
    B = [LI() for _ in range(H)]
    loop = 160*80
    dp = [[False]*(loop) for _ in range(H*W)]
    cur = abs(A[0][0] - B[0][0])
    dp[0][cur] = True
    for i in range(H):
        for j in range(W):
            for k in range(loop):
                if dp[i*W+j][k]:
                    if i<H-1:
                        cur = abs(A[i+1][j] - B[i+1][j])
                        dp[(i+1)*W +j][k + cur] = True
                        dp[(i+1)*W +j][abs(k - cur)] = True
                    if j<W-1:
                        cur = abs(A[i][j+1] - B[i][j+1])
                        dp[i*W+(j+1)][k+cur] = True
                        dp[i*W+(j+1)][abs(k-cur)] = True
    #print(dp[-1])
    ans = inf
    for i,f in enumerate(dp[H*W-1]):
        if f:
            ans = i
            break
    print(ans)
    return

import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    examE2()

Submission status: Time Limit Exceeded

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

H, W = lr()
A = [lr() for _ in range(H)]
B = [lr() for _ in range(H)]
diff = [[0] * W for _ in range(H)]
for i in range(H):
    for j in range(W):
        diff[i][j] = abs(A[i][j] - B[i][j])

dp = [[[False] * 12000 for j in range(W)] for i in range(H)]
dp[0][0][diff[0][0]] = True
for i in range(H):
    for j in range(W):
        for k in range(12000):
            if dp[i][j][k]:
                if i < H-1:
                    dp[i+1][j][abs(k+diff[i+1][j])] = True
                    dp[i+1][j][abs(k-diff[i+1][j])] = True
                if j < W-1:
                    dp[i][j+1][abs(k+diff[i][j+1])] = True
                    dp[i][j+1][abs(k-diff[i][j+1])] = True

for k in range(100):
    if dp[H-1][W-1][k] == True:
        answer = k
        break

print(answer)

Submission status: Time Limit Exceeded

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

H, W = lr()
A = [lr() for _ in range(H)]
B = [lr() for _ in range(H)]
diff = [[0] * W for _ in range(H)]
for i in range(H):
    for j in range(W):
        diff[i][j] = abs(A[i][j] - B[i][j])

dp = [[[False] * 600000 for j in range(W)] for i in range(H)]
dp[0][0][diff[0][0]] = True
for i in range(H):
    for j in range(W):
        for k in range(600000):
            if dp[i][j][k]:
                if i < H-1:
                    dp[i+1][j][abs(k+diff[i+1][j])] = True
                    dp[i+1][j][abs(k-diff[i+1][j])] = True
                if j < W-1:
                    dp[i][j+1][abs(k+diff[i][j+1])] = True
                    dp[i][j+1][abs(k-diff[i][j+1])] = True

for k in range(100):
    if dp[H-1][W-1][k] == True:
        answer = k
        break

print(answer)

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)]
n = (h + w + 1) * 80
dp = [[[False for i in range(n)] for j in range(w)] for k in range(h)]
dp[0][0][abs(a[0][0] - b[0][0])] = True

for i in range(h):
  for j in range(w):
    if i + 1 < h:
      for k in range(n):
        if dp[i][j][k]:
          dp[i + 1][j][k + abs(a[i + 1][j] - b[i + 1][j])] = True
          dp[i + 1][j][abs(k - abs(a[i + 1][j] - b[i + 1][j]))] = True
    if j + 1 < w:
      for k in range(n):
        if dp[i][j][k]:
          dp[i][j + 1][k + abs(a[i][j + 1] - b[i][j + 1])] = True
          dp[i][j + 1][abs(k - abs(a[i][j + 1] - b[i][j + 1]))] = True

for k in range(n):
  if dp[h - 1][w - 1][k]:
    print(k)
    break

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)]
n = 160 * 160
dp = [[[False for i in range(n)] for j in range(w)] for k in range(h)]
dp[0][0][abs(a[0][0] - b[0][0])] = True

for i in range(h):
  for j in range(w):
    if i + 1 < h:
      for k in range(n):
        if dp[i][j][k]:
          dp[i + 1][j][k + abs(a[i + 1][j] - b[i + 1][j])] = True
          dp[i + 1][j][abs(k - abs(a[i + 1][j] - b[i + 1][j]))] = True
    if j + 1 < w:
      for k in range(n):
        if dp[i][j][k]:
          dp[i][j + 1][k + abs(a[i][j + 1] - b[i][j + 1])] = True
          dp[i][j + 1][abs(k - abs(a[i][j + 1] - b[i][j + 1]))] = True

for k in range(n):
  if dp[h - 1][w - 1][k]:
    print(k)
    break

Submission status: Time Limit Exceeded

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

D = [[abs(A[h][w] - B[h][w]) for w in range(W)] for h in range(H)]
table = [[set() for __ in range(W)] for _ in range(H)]
table[0][0] = {D[0][0]}

for h in range(H):
    for w in range(W):
        Dhw = D[h][w]
        table[h][w] |= {x + Dhw for x in table[h - 1][w]} | {abs(x - Dhw) for x in table[h - 1][w]} | \
                       {x + Dhw for x in table[h][w - 1]} | {abs(x - Dhw) for x in table[h][w - 1]}

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

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, input().split())
m = 0
c = [list(map(int, input().split())) for _ in range(h)]
for i in range(h):
  d = list(map(int, input().split()))
  for j in range(w):
    c[i][j] = abs(c[i][j] - d[j])
    m = max(m,c[i][j])
e = [[c[0][0]]]
for j in range(1,w):
  f = []
  for k in e[j-1]:
    f.append(k+c[0][j])
    f.append(abs(k-c[0][j]))
  e.append([g for g in f if g <= m*(h+w-j)])
for i in range(1,h):
  for j in range(w):
    f = []
    p = c[i][j]
    if j>0:
      for k in e[j-1]:
        f.append(k+p)
        f.append(abs(k-p))
    for k in e[j]:
      f.append(k+p)
      f.append(abs(k-p))
    e[j] = [g for g in f if g <= m*(h+w-i-j)]
print(min(e[w-1]))

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, input().split())
c = [list(map(int, input().split())) for _ in range(h)]
for i in range(h):
  d = list(map(int, input().split()))
  for j in range(w):
    c[i][j] = abs(c[i][j] - d[j])
m = max(max(c))
e = [[c[0][0]]]
for j in range(1,w):
  f = []
  for k in e[j-1]:
    f.append(k+c[0][j])
    f.append(abs(k-c[0][j]))
  e.append([g for g in f if g <= m*(h+w-j)])
for i in range(1,h):
  for j in range(w):
    f = []
    if j>0:
      for k in e[j-1]:
        f.append(k+c[i][j])
        f.append(abs(k-c[i][j]))
    for k in e[j]:
      f.append(k+c[i][j])
      f.append(abs(k-c[i][j]))
    e[j] = [g for g in f if g <= m*(h+w-i-j)]
print(min(e[w-1]))

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, input().split())
c = [list(map(int, input().split())) for _ in range(h)]
for i in range(h):
  d = list(map(int, input().split()))
  for j in range(w):
    c[i][j] = abs(c[i][j] - d[j])
m = max(max(c))
e = [[c[0][0]]]
for j in range(1,w):
  f = []
  for k in e[j-1]:
    f.append(k+c[0][j])
    f.append(abs(k-c[0][j]))
  e.append(f)
for i in range(1,h):
  for j in range(w):
    f = []
    if j>0:
      for k in e[j-1]:
        f.append(k+c[i][j])
        f.append(abs(k-c[i][j]))
    for k in e[j]:
      f.append(k+c[i][j])
      f.append(abs(k-c[i][j]))
    f = [g for g in f if g <= m*(h+w-i-j)]
    e[j] = f
print(min(e[w-1]))

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, input().split())
c = [list(map(int, input().split())) for _ in range(h)]
for i in range(h):
  d = list(map(int, input().split()))
  for j in range(w):
    c[i][j] = abs(c[i][j] - d[j])
e = [[c[0][0]]]
for j in range(1,w):
  f = []
  for k in e[j-1]:
    f.append(k+c[0][j])
    f.append(abs(k-c[0][j]))
  e.append(f)
for i in range(1,h):
  for j in range(w):
    f = []
    if j>0:
      for k in e[j-1]:
        f.append(k+c[i][j])
        f.append(abs(k-c[i][j]))
    for k in e[j]:
      f.append(k+c[i][j])
      f.append(abs(k-c[i][j]))
    e[j] = f
print(min(e[w-1]))

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
A = [list(map(int, input().split()))+[0] for _ in range(H)]
B = [list(map(int, input().split()))+[0] for _ in range(H)]
A.append([0]*(W+1))
B.append([0]*(W+1))


dp = [[set([]) for _ in range(W+2)] for _ in range(H+2)]
diff = A[0][0] - B[0][0]
dp[0][0].add(diff)
dp[0][0].add(-diff)

# 配るDP
for h in range(H):
    for w in range(W):
        dif_r = abs(A[h + 1][w] - B[h + 1][w])
        dif_d = abs(A[h][w + 1] - B[h][w + 1])
        for val in dp[h][w]:
            if val + dif_r <= 80:
                dp[h+1][w].add(val+dif_r)
            if val - dif_r <= 80:
                dp[h+1][w].add(val-dif_r)
            if val + dif_d <= 80:
                dp[h][w+1].add(val+dif_d)
            if val - dif_d <= 80:
                dp[h][w+1].add(val-dif_d)

ans = 10 ** 9
for val in dp[H-1][W-1]:
    ans = min(ans, abs(val))

print(ans)

Submission status: Time Limit Exceeded

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

def main():
    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+1][j+1] = abs(grid1[i][j]-grid2[i][j])

    # dp[i][j][k] := グリッド(i, j)に数値kで到達可能かどうか
    dp = list3d(H+1, W+1, MAXV+1, 0)
    dp[1][1][grid[1][1]] = 1
    for i in range(1, H+1):
        for j in range(1, W+1):
            v = grid[i][j]
            for k in range(MAXV+1):
                # 上からの遷移
                dp[i][j][k] |= dp[i-1][j][abs(k-v)]
                if k+v <= MAXV:
                    dp[i][j][k] |= dp[i-1][j][k+v]
                # 左からの遷移
                dp[i][j][k] |= dp[i][j-1][abs(k-v)]
                if k+v <= MAXV:
                    dp[i][j][k] |= dp[i][j-1][k+v]
    ans = INF
    for k in range(MAXV+1):
        if dp[H][W][k]:
            ans = min(ans, k)
    print(ans)
main()

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int,input().split())
dp = [[[0]]]
inf = [[0]*W for i in range(H)]
for i in range(H):
  x = [int(c) for c in input().split()]
  for j in range(W):
    inf[i][j] = x[j]
m = 0
for i in range(H):
  x = [int(c) for c in input().split()]
  for j in range(W):
    inf[i][j] = abs(inf[i][j]-x[j])
    m = max(inf[i][j],m)
M = m*(H+W)+10
dp = [[[0]*M for i in range(W)] for i in range(H)]
x = inf[0][0]
dp[0][0][x] = 1
for i in range(1,H):
  x = inf[i][0]
  for h in range(M):
    if dp[i-1][0][h]==1:
      dp[i][0][h+x] = 1
      dp[i][0][abs(h-x)] = 1

for j in range(1,W):
  x = inf[0][j]
  for h in range(M):
    if dp[0][j-1][h]==1:
      dp[0][j][h+x] = 1
      dp[0][j][abs(h-x)] = 1

for i in range(1,H):
  for j in range(1,W):
    x = inf[i][j]
    for h in range(M):
      if dp[i][j-1][h]==1:
        dp[i][j][h+x] = 1
        dp[i][j][abs(h-x)] = 1
      if dp[i-1][j][h]==1:
        dp[i][j][h+x] = 1
        dp[i][j][abs(h-x)] = 1
for h in range(M):
  if dp[-1][-1][h]==1:
    print(h)
    break

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())
raw = []
for i in range(h):
  raw.append(list(map(int,input().split())))
for i in range(h):
  tmp = list(map(int,input().split()))
  for j in range(w):
    raw[i][j] -= tmp[j]
    raw[i][j] = abs(raw[i][j])
#print(raw)
scale = 80 * 160 + 1
#scale = 21
dp = [[{} for _ in range(w)] for _ in range(h)]
dp[0][0][raw[0][0]] = 1
for i in range(h):
  for j in range(w):
    if i != 0:
      for x in dp[i-1][j].keys():
        dp[i][j][x+raw[i][j]] = 1
        dp[i][j][abs(x-raw[i][j])] = 1
    if j != 0:
      for x in dp[i][j-1].keys():
        dp[i][j][x+raw[i][j]] = 1
        dp[i][j][abs(x-raw[i][j])] = 1
    #print(dp[i][j])
can = sorted(dp[-1][-1].keys())
print(can[0])

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())
raw = []
for i in range(h):
  raw.append(list(map(int,input().split())))
for i in range(h):
  tmp = list(map(int,input().split()))
  for j in range(w):
    raw[i][j] -= tmp[j]
    raw[i][j] = abs(raw[i][j])
#print(raw)
scale = 80 * 160 + 1
#scale = 21
dp = [[[0 for _ in range(scale)] for _ in range(w)] for _ in range(h)]
dp[0][0][raw[0][0]] = 1
for i in range(h):
  for j in range(w):
    if i != 0:
      for d in range(scale):
        if dp[i-1][j][d] == 1:
          dp[i][j][d+raw[i][j]] = 1
          dp[i][j][abs(d-raw[i][j])] = 1
    if j != 0:
      for d in range(scale):
        if dp[i][j-1][d] == 1:
          dp[i][j][d+raw[i][j]] = 1
          dp[i][j][abs(d-raw[i][j])] = 1
    #print(dp[i][j])
#print(dp[-1][-1])
for d in range(scale):
  if dp[-1][-1][d] == 1:
    print(d)
    break

Submission status: Time Limit Exceeded

Solution code:

def main():
    H,W = map(int,input().split())
    A = [list(map(int,input().split())) for _ in range(H)]
    B = [list(map(int,input().split())) for _ in range(H)]
    M = max([abs(a[i]-b[i]) for i in range(W)  for a,b in zip(A,B)])
    dp = {(0,0,abs(A[0][0] - B[0][0])):True}
 
    for w in range(1,W):
        a = A[0][w]
        b = B[0][w]
        for k in range((H + W)*M + 1):
            if (0,w - 1,k) in dp:
                dp[(0,w,k + abs(a - b))] = True
            if  (0,w - 1,k) in dp:
                dp[(0,w,abs(k - abs(a - b)))] = True
    for h in range(1,H):
        a = A[h][0]
        b = B[h][0]
        for k in range((H + W)*M + 1):
            if (h  - 1 , 0 ,k) in dp:
                dp[(h, 0,k + abs(a - b))] = True
            if  (h - 1 , 0,k) in dp:
                dp[(h, 0,abs(k - abs(a - b)))] = True
 
 
    for h in range(1,H):
        for w in range(1,W):
            a = A[h][w]
            b = B[h][w]
            for k in range((H + W)*M + 1):
                if (h - 1,w,k) in dp:
                    dp[(h,w,k + abs(a - b))] = True
                if (h,w - 1,k) in dp:
                    dp[(h,w,k + abs(a - b))] = True
                if  (h - 1,w,k) in dp:
                    dp[(h,w,abs(k - abs(a - b)))] = True
                if  (h,w - 1,k) in dp:
                    dp[(h,w,abs(k - abs(a - b)))] = True
    for i in range((H + W)*M + 1):
        if (H - 1,W - 1,i) in dp:
            print(i)
            return
    return
 
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from math import ceil

def main():
    H,W = map(int,input().split())
    A = [list(map(int,input().split())) for _ in range(H)]
    B = [list(map(int,input().split())) for _ in range(H)]
    M = max([abs(a[i]-b[i]) for i in range(W)  for a,b in zip(A,B)])
    dp = {(0,0,abs(A[0][0] - B[0][0])):True}

    for w in range(1,W):
        a = A[0][w]
        b = B[0][w]
        for k in range((H + W)*M + 1):
            if (0,w - 1,k) in dp:
                dp[(0,w,k + abs(a - b))] = True
            if  (0,w - 1,k) in dp:
                dp[(0,w,abs(k - abs(a - b)))] = True
    for h in range(1,H):
        a = A[h][0]
        b = B[h][0]
        for k in range((H + W)*M + 1):
            if (h  - 1 , 0 ,k) in dp:
                dp[(h, 0,k + abs(a - b))] = True
            if  (h - 1 , 0,k) in dp:
                dp[(h, 0,abs(k - abs(a - b)))] = True


    for h in range(1,H):
        for w in range(1,W):
            a = A[h][w]
            b = B[h][w]
            for k in range((H + W)*M + 1):
                if (h - 1,w,k) in dp:
                    dp[(h,w,k + abs(a - b))] = True
                if (h,w - 1,k) in dp:
                    dp[(h,w,k + abs(a - b))] = True
                if  (h - 1,w,k) in dp:
                    dp[(h,w,abs(k - abs(a - b)))] = True
                if  (h,w - 1,k) in dp:
                    dp[(h,w,abs(k - abs(a - b)))] = True
    for i in range((H + W)*M + 1):
        if (H - 1,W - 1,i) in dp:
            print(i)
            return
    return

if __name__ == "__main__":
    main()