Problem:


Score : 500 points

Problem Statement

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

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

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

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

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

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

Find the minimum unbalancedness possible.

Constraints

2 \leq H \leq 80

2 \leq W \leq 80

0 \leq A_{ij} \leq 80

0 \leq B_{ij} \leq 80

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum unbalancedness possible.

Sample Input 1

2 2
1 2
3 4
3 4
2 1

Sample Output 1

0

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

Sample Input 2

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

Sample Output 2

2



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


Sample output:
0

Submission status: Time Limit Exceeded

Solution code:

h, w = map(int, input().split())
M = []
temp = []
for row in range(h):
    l = list(map(int, input().split()))
    temp.append(l)
for row in range(h):
    l = list(map(int, input().split()))
    R = []
    for col in range(w):
        R.append(abs(l[col] - temp[row][col]))
    M.append(R)

# [[2,3],[3,4]]
SS = []
for row in range(h):
    if row==0:
        for col in range(w):
            if col == 0:
                SS.append(set([M[row][col]]))
            else:
                prev = SS[-1]
                tempset = set()
                for each_num in prev:
                    tempset.add(each_num + M[row][col])
                    tempset.add(abs(each_num - M[row][col]))
                    tempset.add(abs(-each_num + M[row][col]))
                SS.append(tempset)
    else:
        for col in range(w):
            if col == 0:
                prev = SS[col]
                tempset = set()
                for each_num in prev:
                    tempset.add(each_num + M[row][col])
                    tempset.add(abs(each_num - M[row][col]))
                    tempset.add(abs(-each_num + M[row][col]))
                SS[col] = tempset
            else:
                prev = SS[col]
                before = SS[col-1]
                tempset = set()
                for each_num in prev:
                    tempset.add(each_num + M[row][col])
                    tempset.add(abs(each_num - M[row][col]))
                    tempset.add(abs(-each_num + M[row][col]))
                for each_num in before:
                    tempset.add(each_num + M[row][col])
                    tempset.add(abs(each_num - M[row][col]))
                    tempset.add(abs(-each_num + M[row][col]))
                SS[col] = tempset
final = SS[-1]
print(min(list(final)))

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[]]*num
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################


H,W = II()
A = []
B = []
for i in range(H):
    A.append(III())
for i in range(H):
    B.append(III())

def calc(n):
    return n + (H+W-1)*80

d = [[set() for _ in range(W)] for _ in range(H)]
for i in range(H):
    for j in range(W):
        if i==0 and j==0:
            d[i][j].add(calc(A[i][j]-B[i][j]))
            d[i][j].add(calc(-A[i][j]+B[i][j]))
        elif j==0:
            for k in d[i-1][j]:
                    d[i][j].add(k+A[i][j]-B[i][j])
                    d[i][j].add(k-A[i][j]+B[i][j])
        elif i==0:
            for k in d[i][j-1]:
                    d[i][j].add(k+A[i][j]-B[i][j])
                    d[i][j].add(k-A[i][j]+B[i][j])
        else:
            for k in d[i-1][j]:
                    d[i][j].add(k+A[i][j]-B[i][j])
                    d[i][j].add(k-A[i][j]+B[i][j])
            for k in d[i][j-1]:
                    d[i][j].add(k+A[i][j]-B[i][j])
                    d[i][j].add(k-A[i][j]+B[i][j])

ans = 2*(H+W-1)*80+1
for i in d[H-1][W-1]:
        now = abs(i-(H+W-1)*80)
        if ans>now:
            ans = now
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import copy
def main():
    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)]
    seq = list(itertools.combinations(range(w+h-2),w-1))
    route = []
    for i in seq:
        tmp = [1]*(w+h-2)
        for j in i:
            tmp[j] = 0
        route.append(tuple(copy.deepcopy(tmp)))
    ans = 10**9
    for i in route:
        x = 0
        y = 0
        aa = a[y][x]
        bb = b[y][x]
        rb = [(abs(aa-bb),sorted([aa,bb]))]
        for j in i:
            if j == 0:
                x += 1
            else:
                y += 1
            aa = a[y][x]
            bb = b[y][x]
            rb.append((abs(aa-bb),sorted([aa,bb])))
        rb = sorted(rb,reverse=True)
        for i in range(len(rb)):
            p = rb.pop(-1)
            if not p[0] == 0:
                rb.append(p)
                break
        tr = 0
        tb = 0
        lrb = len(rb)
        odd = lrb%2
        for j in range(lrb-odd):
            if j %2 == 0:
                tr += rb[j][1][0]
                tb += rb[j][1][1]
            else:
                tr += rb[j][1][1]
                tb += rb[j][1][0]
        if odd == 1:
            tr,tb = min([tr,tb])+max(rb[-1][1]),max([tr,tb])+min(rb[-1][1])
        ans = min([ans,abs(tr-tb)])
    print(ans)
    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

h, w = map(int, input().split())
grid = [None for _ in range(h)]
poss = [[set() for x in range(w)] for y in range(h)]
tmp = [map(int, input().split()) for _ in range(h * 2)]
for i, (l1, l2) in enumerate(zip(tmp, tmp[h:])):
	grid[i] = [abs(x - y) for x, y in zip(l1, l2)]
q = deque([(0, 0)])
poss[0][0].add(-grid[0][0])
poss[0][0].add(grid[0][0])
while q:
	cx, cy = q.popleft()
	for dx, dy in ((1, 0), (0, 1)):
		nx = cx + dx
		ny = cy + dy
		if not (0 <= nx <= w - 1 and 0 <= ny <= h - 1):
			continue
		m = grid[ny][nx]
		poss[ny][nx] |= set(l + m for l in poss[cy][cx])
		poss[ny][nx] |= set(l - m for l in poss[cy][cx])
		q.append((nx, ny))
print(min(abs(x) for x in poss[-1][-1]))

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

arr = [set() for _ in range(W)]
arr[0].add(0)
for y in range(H):
    nextarr = [set() for _ in range(W)]
    Ay = A[y]
    By = B[y]
    dh = H - y - 1
    for x in range(W):
        nextset = nextarr[x]
        d = Ay[x] - By[x]
        dw = W - x - 1
        lim = (dh + dw + 1) * 160
        for n in arr[x]:
            if abs(n+d) <= lim:
                nextset.add(n+d)
            if abs(n-d) <= lim:
                nextset.add(n-d)
        if x >= 1:
            for n in nextarr[x-1]:
                if abs(n+d) <= lim:
                    nextset.add(n+d)
                if abs(n-d) <= lim:
                    nextset.add(n-d)
    arr = nextarr
print(min([abs(d) for d in arr[-1]]))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
MAX_VAL = 10000
OFFSET = MAX_VAL // 2

h, w = [int(item) for item in input().split()]
a = []
b = []
for i in range(h):
    line = [int(item) for item in input().split()] + [0]
    a.append(line)
a.append([0] * (w + 1))
for i in range(h):
    line = [int(item) for item in input().split()] + [0]
    b.append(line)
b.append([0] * (w + 1))

# dp[height][width][bias]
dp = [[set() for _ in range(w+1)] for _ in range(h+1)] 
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):
        diffr = a[i][j+1] - b[i][j+1]
        diffd = a[i+1][j] - b[i+1][j]
        for item in dp[i][j]:
            # Move right
            dp[i][j+1].add(item+diffr)
            dp[i][j+1].add(item-diffr)
            # Move down
            dp[i+1][j].add(item+diffd)
            dp[i+1][j].add(item-diffd)
ans = 10**9
for item in dp[h-1][w-1]:
    ans = min(ans, abs(item))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq
import bisect
 
mod = 10**9+7
 
def I(): return(int(sys.stdin.readline()))
def LI(): return([int(x) for x in sys.stdin.readline().split()])
def S(): return(list(sys.stdin.readline())[:-1])
 
def main():
    H,W = LI()
    A = [LI() for _ in range(H)]
    B = [LI() for _ in range(H)]
    D = [[abs(A[h][w]-B[h][w]) for w in range(W)] for h in range(H)]
    dp = [[set() for w in range(W)] for h in range(H)]

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

    for h in range(H):
        for w in range(W):
            if(h>0):
                for s in dp[h-1][w]:
                    dp[h][w].add(abs(s+D[h][w]))
                    dp[h][w].add(abs(s-D[h][w]))
            if(w>0):
                for s in dp[h][w-1]:
                    dp[h][w].add(abs(s+D[h][w]))
                    dp[h][w].add(abs(s-D[h][w]))
    return(min(dp[H-1][W-1]))
 
if __name__ == "__main__":
    print(main())

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
INF = 10**10

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

C = [[abs(a - b) for a, b in zip(rowA, rowB)] for rowA, rowB in zip(A, B)]

D = [[set() for _ in range(W)] for _ in range(H)]
D[0][0].add(0)

for h in range(H):
    for w in range(W):
        if h < H - 1:
            for d in D[h][w]:
                D[h + 1][w].add(d + C[h][w])
                D[h + 1][w].add(d - C[h][w])
        if w < W - 1:
            for d in D[h][w]:
                D[h][w + 1].add(d + C[h][w])
                D[h][w + 1].add(d - C[h][w])

ans = INF
c = C[H - 1][W - 1]
for d in D[H - 1][W - 1]:
    ans = min(ans, abs(d - c), abs(d + c))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())
al = []
for _ in range(h):
    a = list(map(int,input().split()))
    al.append(a)

bl = []
for _ in range(h):
    b = list(map(int,input().split()))
    bl.append(b)

abl = [[0 for _ in range(w)] for _ in range(h)]
for i in range(h):
    for j in range(w):
        abl[i][j] = al[i][j] - bl[i][j]

from collections import defaultdict
dic = defaultdict(set)

dic[(0,0)].add(abl[0][0])
dic[(0,0)].add(-abl[0][0])
for i in range(h):
    for j in range(w):
        for v in dic[(i,j)]:
            if j + 1 < w:
                if -6400 <= v+abl[i][j+1] <= 6400:
                    dic[(i,j+1)].add(v+abl[i][j+1])
                if -6400 <= v-abl[i][j+1] <= 6400:
                    dic[(i,j+1)].add(v-abl[i][j+1])
            if i + 1 < h:
                if -6400 <= v+abl[i+1][j] <= 6400:
                    dic[(i+1,j)].add(v+abl[i+1][j])
                if -6400 <= v-abl[i+1][j] <= 6400:
                    dic[(i+1,j)].add(v-abl[i+1][j])

ans = float("inf")
for i in dic[(h-1, w-1)]:
    ans = min(abs(i), ans)
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_list=list(map(int,input().split()))
    A.append(a_list)
B=[]
for i in range(h):
    b_list=list(map(int,input().split()))
    B.append(b_list)
dp=[set() for i in range(w)]
dp[0].add(0)
for i in range(h):
    for j in range(w):
        s=set()
        for x in dp[j]:
            y=abs(x+(A[i][j]-B[i][j]))
            z=abs(x+(B[i][j]-A[i][j]))
            s.add(y)
            s.add(z)
        dp[j]=s
        if j<w-1:
            dp[j+1]=s|dp[j+1]
ans=min(dp[w-1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:

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

A = []

for i in range(H):

    a = list(map(int,input().split()))
    A.append(a)

B = []

for i in range(H):

    b = list(map(int,input().split()))
    B.append(b)

for i in range(H):
    for j in range(W):

        A[i][j] = abs(A[i][j] - B[i][j])

C = [[] for i in range(H)]
for i in range(H):
    for j in range(W):
        
        C[i].append({})

#print (C)

for i in range(H):

    if i == 0:
        C[i][0][A[i][0]] = 1
    else:

        for j in C[i-1][0]:
            C[i][0] [abs(j - A[i][0])] = 1
            C[i][0] [abs(j + A[i][0])] = 1

for j in range(W):
    if j == 0:
        continue
    else:
        for i in C[0][j-1]:
            C[0][j] [abs(i - A[0][j])] = 1
            C[0][j] [abs(i + A[0][j])] = 1

#print (C)

for i in range(H-1):
    i += 1

    for j in range(W-1):
        j += 1

        for k in C[i-1][j]:

            if abs(k + A[i][j]) <= (H-i + W-j) * 80:
                C[i][j] [abs(k + A[i][j])] = 1   
            C[i][j] [abs(k - A[i][j])] = 1
        for k in C[i][j-1]:
            if abs(k + A[i][j]) <= (H-i + W-j) * 80:
                C[i][j] [abs(k + A[i][j])] = 1
            C[i][j] [abs(k - A[i][j])] = 1

#print (C)
ans = float("inf")   
for i in C[-1][-1]:

    ans = min(ans,i)
    
print (ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353


H, W = list(map(int, sys.stdin.buffer.readline().split()))
A = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(H)]
B = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(H)]

grid = [[0] * W for _ in range(H)]
for h, w in itertools.product(range(H), range(W)):
    grid[h][w] = A[h][w] - B[h][w]

# 符号をどっちにするか選べる
dp = [[set() for _ in range(W)] for _ in range(H)]
dp[0][0] = {grid[0][0], -grid[0][0]}
for h, w in itertools.product(range(H), range(W)):
    g = grid[h][w]
    s = dp[h][w]
    limit = (H - h + 1) * (W - w + 1) * 80
    if h - 1 >= 0:
        for c in dp[h - 1][w]:
            if abs(c + g) <= limit:
                s.add(abs(c + g))
            if abs(c - g) <= limit:
                s.add(abs(c - g))
    if w - 1 >= 0:
        for c in dp[h][w - 1]:
            if abs(c + g) <= limit:
                s.add(abs(c + g))
            if abs(c - g) <= limit:
                s.add(abs(c - g))

ans = INF
for s in dp[-1][-1]:
    ans = min(ans, abs(s))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    h,w = LI()
    a = LIR(h)
    b = LIR(h)
    for i in range(h):
        for j in range(w):
            a[i][j] -= b[i][j]
            if a[i][j] < 0:
                a[i][j] *= -1
    f = defaultdict(lambda : set({}))
    f[(0,0)].add(a[0][0])
    d = [(0,1),(1,0)]
    Ma = [[160*(h+w-x-y) for x in range(w)] for y in range(h)]
    for y in range(h):
        for x in range(w):
            for t in f[(y,x)]:
                for dy,dx in d:
                    ny = y+dy
                    nx = x+dx
                    if 0 <= ny < h and 0 <= nx < w:
                        M = Ma[ny][nx]
                        m = -M
                        nt = t-a[ny][nx]
                        if m <= nt <= M:
                            f[(ny,nx)].add(nt)
                        nt = t+a[ny][nx]
                        if m <= nt <= M:
                            f[(ny,nx)].add(nt)
    ans = min([abs(i) for i in f[(h-1,w-1)]])
    print(ans)
    return

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

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())

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

tmp = [[{} for _ in range(W)] for _ in range(H)]
tmp[0][0] = {(A[0][0], B[0][0])}

for height in range(H):
    for width in range(W):
        if height == 0 and width == 0:
            continue
        av = A[height][width]
        bv = B[height][width]
        wa = set()
        if height > 0:
            value = tmp[height-1][width]
            wa = wa.union(map(lambda x: (x[0] + av, x[1] + bv), value))
            wa = wa.union(map(lambda x: (x[0] + bv, x[1] + av), value))
        if width > 0:
            value = tmp[height][width-1]
            wa = wa.union(map(lambda x: (x[0] + av, x[1] + bv), value))
            wa = wa.union(map(lambda x: (x[0] + bv, x[1] + av), value))
        tmp[height][width] = wa

ans = min(tmp[H-1][W-1], key=lambda x: abs(x[0] - x[1]))
print(abs(ans[0] - ans[1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
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)]

AB=[[0]*W for _ in range(H)]
for i in range(H):
  for j in range(W):
    AB[i][j]=abs(A[i][j]-B[i][j])
    
def dfs(i,j,bias):
  global ans
  if i==H-1 and j==W-1:
    ans=min(ans,abs(bias))
  else:
    for k in range(2):
      if k==0:
        if i+1<H:
          for pm in 1,-1:
            dfs(i+1,j,bias+pm*AB[i+1][j])
      else:
        if j+1<W:
          for pm in 1,-1:
            dfs(i,j+1,bias+pm*AB[i][j+1])
  
ans=float("inf")
dfs(0,0,AB[0][0])
dfs(0,0,-AB[0][0])

print(ans)

Submission status: Time Limit Exceeded

Solution code:

h, w = map(int, input().split())
M = []
temp = []
for row in range(h):
    l = list(map(int, input().split()))
    temp.append(l)
for row in range(h):
    l = list(map(int, input().split()))
    R = []
    for col in range(w):
        R.append(abs(l[col] - temp[row][col]))
    M.append(R)

SS = []
for row in range(h):
    if row==0:
        for col in range(w):
            if col == 0:
                SS.append(set([M[row][col], -M[row][col]]))
            else:
                prev = SS[-1]
                tempset = set()
                for each_num in prev:
                    tempset.add(each_num + M[row][col])
                    tempset.add(each_num - M[row][col])
                SS.append(tempset)
    else:
        for col in range(w):
            if col == 0:
                prev = SS[col]
                tempset = set()
                for each_num in prev:
                    tempset.add(each_num + M[row][col])
                    tempset.add(each_num - M[row][col])
                SS[col] = tempset
            else:
                prev = SS[col]
                before = SS[col-1]
                tempset = set()
                for each_num in prev:
                    tempset.add(each_num + M[row][col])
                    tempset.add(each_num - M[row][col])
                for each_num in before:
                    tempset.add(each_num + M[row][col])
                    tempset.add(each_num - M[row][col])
                SS[col] = tempset
final = SS[-1]
for i in range(80 * 80):
    if i in final:
        print(i)
        break

Submission status: Time Limit Exceeded

Solution code:
def dp(A, B, h, w, target):
    abs_diff = abs(A[h][w] - B[h][w])
    if h==0 and w==0:
        ans = abs(target - abs_diff)
    elif h==0:
        ans3 = dp(A, B, h, w-1, target + abs_diff)
        ans4 = dp(A, B, h, w-1, target - abs_diff)
        ans = min(ans3, ans4)
    elif w==0:
        ans1 = dp(A, B, h-1, w, target + abs_diff)
        ans2 = dp(A, B, h-1, w, target - abs_diff)
        ans = min(ans1, ans2)
    else:
        ans1 = dp(A, B, h-1, w, target + abs_diff)
        ans2 = dp(A, B, h-1, w, target - abs_diff)
        ans3 = dp(A, B, h, w-1, target + abs_diff)
        ans4 = dp(A, B, h, w-1, target - abs_diff)
        ans = min(ans1, ans2, ans3, ans4)
    return ans


H, W = map(int, input().split())
A = []
B = []
for i in range(H):
    A.append([int(i) for i in input().split()])
for i in range(H):
    B.append([int(i) for i in input().split()])
    
ans = dp(A, B, H-1, W-1, 0)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
from collections import defaultdict
from itertools import product
def resolve():
    h,w=map(int,input().split())
    A=[list(map(int,input().split())) for _ in range(h)]
    B=[list(map(int,input().split())) for _ in range(h)]
    dp=[[defaultdict(int) for _ in range(w)] for _ in range(h)]
    x=A[-1][-1]-B[-1][-1]
    dp[-1][-1][x]=1
    dp[-1][-1][-x]=1

    for i,j in product(range(h-1,-1,-1),range(w-1,-1,-1)):
        x=A[i][j]-B[i][j]
        if(i+1<h):
            for key,val in dp[i+1][j].items():
                if(val==1):
                    dp[i][j][key+x]=1
                    dp[i][j][key-x]=1
        if(j+1<w):
            for key,val in dp[i][j+1].items():
                if(val==1):
                    dp[i][j][key+x]=1
                    dp[i][j][key-x]=1

    ans=INF
    for key,val in dp[0][0].items():
        if(val==1): ans=min(ans,abs(key))

    print(ans)
resolve()

Submission status: Time Limit Exceeded

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

def solve():
    H, W = map(int, input().split())
    Ass = [tuple(map(int, input().split())) for _ in range(H)]
    Bss = [tuple(map(int, input().split())) for _ in range(H)]

    dp = [[set() for j in range(W)] for i in range(H)]
    A, B = Ass[0][0], Bss[0][0]
    dp[0][0] = set([abs(A-B)])

    for i in range(H):
        for j in range(W):
            if i < H-1:
                A, B = Ass[i+1][j], Bss[i+1][j]
                for diff in dp[i][j]:
                    dp[i+1][j].add(abs(diff+A-B))
                    dp[i+1][j].add(abs(diff+B-A))
            if j < W-1:
                A, B = Ass[i][j+1], Bss[i][j+1]
                for diff in dp[i][j]:
                    dp[i][j+1].add(abs(diff+A-B))
                    dp[i][j+1].add(abs(diff+B-A))

#    for dpi in dp:
#        print(dpi)
    ans = min(dp[-1][-1])
    print(ans)


solve()

Submission status: Time Limit Exceeded

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

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

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

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

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

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

DP[0]=[SA[0][0]]

for i in range(H):
    NDP=[[] for _ in range(W)]
    for j in range(W):
        for k in set(DP[j]):
            if k>=6400:
                continue
            if i+1<H:
                NDP[j].append(k+SA[i+1][j])
                NDP[j].append(abs(k-SA[i+1][j]))
                
            if j+1<W:
                DP[j+1].append(k+SA[i][j+1])
                DP[j+1].append(abs(k-SA[i][j+1]))

    if i==H-1:
        print(min(DP[-1]))
        break
    DP=NDP

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)]
c=[[abs(a[i][j]-b[i][j])for j in range(w)]for i in range(h)]
d=[[set()for i in range(w+1)]for j in range(h+1)]
def f(x,y):
    if x==1 and y==1:
        d[1][1]=set([-c[0][0],c[0][0]])
    else:
        a=d[x-1][y]|d[x][y-1]
        e=set()
        for i in a:
            e.add(i-c[x-1][y-1])
            e.add(i+c[x-1][y-1])
        d[x][y]=e
    if x!=h:
        f(x+1,y)
    if y!=w:
        f(x,y+1)
f(1,1)
print(abs(min(d[h][w],key=abs)))

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
A = []
for i in range(H):
  As = list(map(int, input().split()))
  A.append(As)
for i in range(H):
  As = A[i]
  Bs = list(map(int, input().split()))
  for j in range(W):
    A[i][j] = abs(As[j]-Bs[j])
#print(A)
C = [[set() for j in range(W)] for i in range(H)]
C[0][0].add(A[0][0])
for i in range(1, H):
  a = A[i][0]
  for c in C[i-1][0]:
    C[i][0].add(c+a)
    C[i][0].add(abs(c-a))
for j in range(1, W):
  a = A[0][j]
  for c in C[0][j-1]:
    C[0][j].add(c+a)
    C[0][j].add(abs(c-a))
for i in range(1, H):
  for j in range(1, W):
    a = A[i][j]
    l = []
    for c in C[i-1][j]:
      l.append(c+a)
      l.append(abs(c-a))
    for c in C[i][j-1]:
      l.append(c+a)
      l.append(abs(c-a))
    C[i][j] = set(l)
#print(C)
r = min(C[-1][-1])
print(r)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)
# input = sys.stdin.readline
# from bisect import *
# from collections import *
# from heapq import *
# import functools
# import itertools
# import math
INF = 500000
MOD = 10**9+7

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)]
dp = [[{} for j in range(W)] for i in range(H)]
dp[0][0][A[0][0]-B[0][0]] = dp[0][0][-A[0][0]+B[0][0]] = True
for i in range(H):
    for j in range(W):
        for k in dp[i][j]:
            if j+1 < W:
                dp[i][j+1][k+A[i][j+1]-B[i][j+1]] = dp[i][j+1][k-A[i][j+1]+B[i][j+1]] = True
            if i+1 < H:
                dp[i+1][j][k+A[i+1][j]-B[i+1][j]] = dp[i+1][j][k-A[i+1][j]+B[i+1][j]] = True
ks = dp[H-1][W-1].keys()
ans = min(ks, key = lambda x : abs(x))
print(abs(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)]
diff = [[abs(aij - bij) for aij, bij in zip(ai, bi)] for ai, bi in zip(a, b)]
maxd = 80 * 80 + 1

memo = [[[None] * maxd for x in range(w)] for y in range(h)]
def doit(x, y, d):
    if x < 0 or y < 0 or d > 160:
        return False
    if x == 0 and y == 0:
        return d == diff[0][0]
    if memo[y][x][d] is None:
        memo[y][x][d] = (doit(x - 1, y, abs(d + diff[y][x])) or
                         doit(x - 1, y, abs(d - diff[y][x])) or
                         doit(x, y - 1, abs(d + diff[y][x])) or
                         doit(x, y - 1, abs(d - diff[y][x])))
    return memo[y][x][d]

for ret in range(maxd):
    if doit(w - 1, h - 1, ret):
        print(ret)
        break

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from copy import copy

row, column = map(int, input().split())
map1 = [list(map(int, input().split())) for _ in range(row)]
map2 = [list(map(int, input().split())) for _ in range(row)]
map_ = [[n1 - n2 for n1, n2 in zip(row1, row2)] for row1, row2 in zip(map1, map2)]

n = map_[0][0]
queue = deque([(0, 0, n), (0, 0, -n)])
ansque = deque()

def bfs(queue):
    while True:
        nextqueue = deque()
        while queue:
            posr, posc, n = queue.popleft()
            if (posr, posc) == (row - 1, column - 1):
                ansque.append(abs(n))
            for dr, dc in zip([1, 0], [0, 1]):
                nextr = posr + dr
                nextc = posc + dc
                if 0 <= nextr < row and 0 <= nextc < column:
                    nextn = map_[nextr][nextc]
                    nextqueue.append((nextr, nextc, n + nextn))
                    nextqueue.append((nextr, nextc, n - nextn))
        if nextqueue:
            queue = copy(nextqueue)
        else:
            return ansque

print(min(bfs(queue)))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
h, w = map(int,input().split())
A = [list(map(int,input().split())) for i in range(h)]
B = [list(map(int,input().split())) for i in range(h)]

C = [[0] * 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])

V = [[2] * w for i in range(h)]
for i in range(h):
    V[i][0] -= 1
for i in range(w):
    V[0][i] -= 1

l = 6600
m = 0

M = [[[0] * l for i in range(w)] for j in range(h)]
N = [[0 for i in range(w)] for j in range(h)]
N[0][0] = C[0][0]

s = 0
Q = [[0, 0]]

M[0][0][C[0][0]] = 1
# M[0][0][m-C[0][0]] = 1

while len(Q) > s:
    i = Q[s][0]
    j = Q[s][1]
    if i+1 < h:
        for ii in range(min(N[i][j]+1, l)):
            if M[i][j][ii] == 1:
                if abs(ii+C[i+1][j]) < l:
                    M[i+1][j][abs(ii+C[i+1][j])] = 1
                if abs(ii-C[i+1][j]) < l:
                    M[i+1][j][abs(ii-C[i+1][j])] = 1
        V[i+1][j] -= 1
        # print(N[i+1][j], N[i][j] + C[i+1][j])
        N[i+1][j] = max(N[i+1][j], N[i][j] + C[i+1][j])
        if V[i+1][j]==0:
            Q.append([i+1,j])
    if j+1 < w:
        for ii in range(min(N[i][j]+1, l)):
            if M[i][j][ii] == 1:
                if abs(ii+C[i][j+1]) < l:
                    M[i][j+1][abs(ii+C[i][j+1])] = 1
                if abs(ii-C[i][j+1]) < l:
                    M[i][j+1][abs(ii-C[i][j+1])] = 1
        V[i][j+1] -= 1
        N[i][j+1] = max(N[i][j+1], N[i][j] + C[i][j+1])
        if V[i][j+1]==0:
            Q.append([i,j+1])
        
    
    s += 1

# print(M[-1][-1])

ans = 10**5
for i in range(len(M[-1][-1])):
    if M[-1][-1][i] == 1:
        ans = i
        break
print(ans)

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=[list(map(int,input().split())) for i in range(h)]
B=[list(map(int,input().split())) for i in range(h)]
a=[set() for j in range(w)]
dp=[copy.deepcopy(a) for i in range(h)]
# for di in dp:
#     print(*dp)
# dp[0][0]=set()
dp[0][0].add(abs(A[0][0]-B[0][0]))
# print(dp)
# for di in dp:
#     print(*dp)
for i in range(h):
    for j in range(w):
        # dp[i][j]=set()
        d=abs(A[i][j]-B[i][j])
        if i-1>=0:
            for si in dp[i-1][j]:
                dp[i][j].add(si+d)
                dp[i][j].add(abs(si-d))
        # print(dp[i][j])
        if j-1>=0:
            for si in dp[i][j-1]:
                dp[i][j].add(si+d)
                dp[i][j].add(abs(si-d))
        # print(dp[i][j])
ans=min(dp[h-1][w-1])
print(ans)
# for di in dp:
#     print(di)