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())
maxK=80*80+1
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 for _ in range(maxK+1)] for _ in range(W+1)] for _ in range(H+1)]
dp[1][1][C[0][0]]=1
for i in range(1, H+1):
    for j in range(1, W+1):
        for k in range(maxK):
            if dp[i-1][j][k]==1 or dp[i][j-1][k]==1:
                k_candidate1, k_candidate2=abs(k-C[i-1][j-1]), abs(k+C[i-1][j-1])
                if k_candidate1<maxK:
                    dp[i][j][k_candidate1]=1
                if k_candidate2<maxK:
                    dp[i][j][k_candidate2]=1
for k in range(maxK):
    if dp[H][W][k]==1:
        print(k)
        break

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(H)]
B = [list(map(int, input().split())) for _ in range(H)]
 
D = [[abs(A[h][w] - B[h][w]) for w in range(W)] for h in range(H)]
DP = [[set() for _ in range(W + 1)] for _ in range(H + 1)]
DP[0][1].add(0)
 
for w in range(W):
    for h in range(H):
        for dp in DP[h][w + 1] | DP[h + 1][w]:
            DP[h + 1][w + 1].add(dp + D[h][w])
            DP[h + 1][w + 1].add(abs(dp - D[h][w]))
 
print(min(DP[H][W]))

Submission status: Time Limit Exceeded

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

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

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

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

Submission status: Time Limit Exceeded

Solution code:
def read_values():
    return map(int, input().split())


def read_list():
    return list(map(int, input().split()))


def read_lists(N):
    return [read_list() for n in range(N)]


def main():
    H, W = read_values()
    A = read_lists(H)
    B = read_lists(H)

    C = [[abs(a0 - b0) for a0, b0 in zip(a, b)] for a, b in zip(A, B)]
    M = sum(map(sum, C))

    dp = [[set() for w in range(W)] for h in range(H)]

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

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

                if w + 1 < W:
                    dp[h][w + 1].add(k + C[h][w + 1])
                    dp[h][w + 1].add(abs(k - C[h][w + 1]))

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def e_balanced_path():
    H, W = [int(i) for i in input().split()]
    A = [[int(i) for i in input().split()] for j in range(H)]
    B = [[int(i) for i in input().split()] for j in range(H)]

    dp = [[set() for j in range(W)] for i in range(H)]
    diff = [[abs(A[i][j] - B[i][j]) for j in range(W)] for i in range(H)]

    dp[0][0].add(diff[0][0])
    for row in range(H):
        for col in range(W):
            for dr, dc in ((1, 0), (0, 1)):
                nr, nc = row + dr, col + dc
                if not (0 <= nr < H and 0 <= nc < W):
                    continue
                for k in dp[row][col]:
                    dp[nr][nc].add(k + diff[nr][nc])
                    dp[nr][nc].add(abs(k - diff[nr][nc]))
    return min(dp[H - 1][W - 1])

print(e_balanced_path())

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def calc_min_abs(routes):
  ans = float('inf')
  for i in range(2**(len(routes))):
    flags = bin(i)[2:].zfill(len(routes))
    val1,val2 = 0,0
    for ii in range(len(flags)):
      iii,jjj = routes[ii]
      if flags[ii] == '0':
        val1 += A[jjj][iii]
        val2 += B[jjj][iii]
      else:
        val1 += B[jjj][iii]
        val2 += A[jjj][iii]

    ans = min(ans,abs(val1-val2))
  return ans

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

q = deque()
q.append([0,0,[[0,0]]])
ans = float('inf')
while len(q) > 0:
  prvi, prvj, routes = q.pop()  
  for i, j in [[prvi+1,prvj], [prvi,prvj+1]]:
    if i >= W or j>= H: continue
    if [i,j] == [W-1,H-1]:
      ans = min(ans, calc_min_abs(routes + [[i,j]]))
    else:
      q.append([i, j, routes + [[i,j]]])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, input().split())
inf = float('INF')
A = []
B = []

for i in range(h):
    line = list(map(int, input().split()))
    A.append(line)

for i in range(h):
    line = list(map(int, input().split()))
    B.append(line)

D = [[0]*w for i in range(h)]
for i in range(h):
    for j in range(w):
        D[i][j] = abs(A[i][j] - B[i][j])


def slide_down(y, x, possible: set):
    new = set()
    delta = D[y+1][x]
    for num in possible:
        if num + delta <=16000:
            new.add(num+delta)
        if abs(num-delta) <= 16000:
            new.add(abs(num-delta))
    return new


def slide_right(y, x, possible: set):
    new = set()
    delta = D[y][x+1]
    for num in possible:
        if num + delta <=16000:
            new.add(num+delta)
        if abs(num-delta) <=16000:
            new.add(abs(num-delta))
    return new


DP = [[set() for j in range(w)] for i in range(h)]
DP[0][0] = {D[0][0]}
for row in range(h):
    for col in range(w):
        possible = DP[row][col]
        if col < w-1:
            new = slide_right(row, col, possible)
            DP[row][col+1] |= new
        if row < h-1:
            new = slide_down(row, col, possible)
            DP[row+1][col] |= new

ans = min(DP[h-1][w-1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    import random
    n=random.randint(4,16)
    a=sorted([random.randint(0,5) for _ in range(n)])[::-1]
    return n,a

show_flg=False
show_flg=True

h,w=LI()
ans=0
a=[[0]*(1+w)]
b=[[0]*(1+w)]
for i in range(h):
    a.append([0]+LI())
for i in range(h):
    b.append([0]+LI())

dp=[[set() for i in range(w+1)]for j in range(h+1)]

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

for i in range(1,h+1):
    for j in range(1,w+1):
        d=a[i][j]-b[i][j]
        for x in dp[i-1][j]:
            if -7000<=x+d<=7000:dp[i][j].add(x+d)
            if -7000<=x-d<=7000:dp[i][j].add(x-d)

        for x in dp[i][j-1]:
            if -7000<=x+d<=7000:dp[i][j].add(x+d)
            if -7000<=x-d<=7000:dp[i][j].add(x-d)

ans=min([abs(i) for i in dp[h][w]])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    import random
    n=random.randint(4,16)
    a=sorted([random.randint(0,5) for _ in range(n)])[::-1]
    return n,a

show_flg=False
show_flg=True

h,w=LI()
ans=0
a=[[0]*(1+w)]
b=[[0]*(1+w)]
for i in range(h):
    a.append([0]+LI())
for i in range(h):
    b.append([0]+LI())

dp=[[set() for i in range(w+1)]for j in range(h+1)]

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

for i in range(1,h+1):
    for j in range(1,w+1):
        d=a[i][j]-b[i][j]
        for x in dp[i-1][j]:
            dp[i][j].add(x+d)
            dp[i][j].add(x-d)

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

ans=min([abs(i) for i in dp[h][w]])

print(ans)

Submission status: Time Limit Exceeded

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

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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())
mp = {}
for i in range(2):
    for j in range(h):
        tmp = input().split()
        for k in range(w):
            mp[(k,j,i)] = int(tmp[k])
mp2 = {}
for i in range(h):
    for j in range(w):
        mp2[(j,i)] = abs(mp[(j,i,0)]-mp[(j,i,1)])

mp3 = [[set() for e in range(h)] for i in range(w)]
mp3[0][0].add(mp2[(0,0)])
# print(mp3)
for i in range(w):
    for j in range(h):
        for k in mp3[i][j]:
            if i < w -1:
                a = mp2[(i+1,j)]
                mp3[i+1][j].add(abs(k-a))
                mp3[i+1][j].add(abs(k+a))
            if j < h -1:
                a = mp2[(i,j+1)]
                mp3[i][j+1].add(abs(k-a))
                mp3[i][j+1].add(abs(k+a))
print(min(mp3[w-1][h-1]))

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)
    mab = [[abs(a[y][x]-b[y][x]) for x in range(w)] for y in range(h)]
    ab = abs(a[0][0] - b[0][0])
    hw = h + w
    dp = [[0] * w for i in range(h)]
    dp[0][0] = 1 << ab
    for i in range(1, h + w - 1):
        mhw = (hw - i) * 80
        for x in range(w):
            y = i - x - 1
            if 0 <= x < w and 0 <= y < h:
                values = dp[y][x]
                value = [z for z in range(values.bit_length()) if values & (1 << z) and z <= mhw]
            else:
                continue
            for mx, my in [[0, 1], [1, 0]]:
                mx += x
                my += y
                if 0 <= mx < w and 0 <= my < h:
                    mxy = mab[my][mx]
                    for v in value:
                        dp[my][mx] |= (1 << abs(v - mxy)) | (1 << (mxy + v))
    ans = dp[-1][-1]
    for i in range(ans.bit_length()):
        if ans & (1 << i):
            print(i)
            return
    return


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

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)
    mab = [[abs(a[y][x]-b[y][x]) for x in range(w)] for y in range(h)]
    ab = abs(a[0][0] - b[0][0])
    hw = h + w
    dp = [[0] * w for i in range(h)]
    dp[0][0] = 1 << ab
    for i in range(1, h + w - 1):
        mhw = (hw - i) * 80
        for x in range(min(i, w)):
            y = i - x - 1
            if 0 <= x < w and 0 <= y < h:
                values = dp[y][x]
                value = [z for z in range(values.bit_length()) if values & (1 << z) and z <= mhw]
            else:
                continue
            for mx, my in [[0, 1], [1, 0]]:
                mx += x
                my += y
                if 0 <= mx < w and 0 <= my < h:
                    mxy = mab[my][mx]
                    for v in value:
                        dp[my][mx] |= (1 << abs(v - mxy)) | (1 << (mxy + v))
    ans = dp[-1][-1]
    for i in range(ans.bit_length()):
        if ans & (1 << i):
            print(i)
            return
    return


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

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)
    mab = [[abs(a[y][x]-b[y][x]) for x in range(w)] for y in range(h)]
    ab = abs(a[0][0] - b[0][0])
    hw = (h + w) * 40
    dp = [[0] * w for i in range(h)]
    dp[0][0] = 1 << ab
    for i in range(1, h + w - 1):
        for x in range(min(i, w)):
            y = i - x - 1
            if 0 <= x < w and 0 <= y < h:
                values = dp[y][x]
                value = [z for z in range(values.bit_length()) if values & (1 << z) and z <= hw]
            else:
                continue
            for mx, my in [[0, 1], [1, 0]]:
                mx += x
                my += y
                if 0 <= mx < w and 0 <= my < h:
                    mxy = mab[my][mx]
                    for v in value:
                        dp[my][mx] |= (1 << abs(v - mxy)) | (1 << (mxy + v))
    ans = dp[-1][-1]
    for i in range(ans.bit_length()):
        if ans & (1 << i):
            print(i)
            return
    return


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

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
#!/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)
    mab = [[abs(a[y][x]-b[y][x]) for x in range(w)] for y in range(h)]
    ab = abs(a[0][0] - b[0][0])
    dp = [[0] * w for i in range(h)]
    dp[0][0] = 1 << ab
    for i in range(1, h + w - 1):
        for x in range(min(i, w)):
            y = i - x - 1
            if 0 <= x < w and 0 <= y < h:
                values = dp[y][x]
                value = [i for i in range(values.bit_length()) if values & (1 << i)]
            else:
                continue
            for mx, my in [[0, 1], [1, 0]]:
                mx += x
                my += y
                if 0 <= mx < w and 0 <= my < h:
                    mxy = mab[my][mx]
                    for v in value:
                        dp[my][mx] |= (1 << abs(v - mxy)) | (1 << (mxy + v))
    ans = dp[-1][-1]
    for i in range(ans.bit_length()):
        if ans & (1 << i):
            print(i)
            return
    return


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

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])
    dp = [[0] * w for i in range(h)]
    dp[0][0] = 1 << ab
    for i in range(1, h + w - 1):
        for x in range(min(i, w)):
            y = i - x - 1
            if 0 <= x < w and 0 <= y < h:
                values = dp[y][x]
                value = [i for i in range(values.bit_length()) if values & (1 << i)]
            else:
                continue
            for mx, my in [[0, 1], [1, 0]]:
                mx += x
                my += y
                if 0 <= mx < w and 0 <= my < h:
                    mxy = abs(a[my][mx] - b[my][mx])
                    for v in value:
                        dp[my][mx] |= (1 << abs(v - mxy)) | (1 << (mxy + v))
    ans = dp[-1][-1]
    for i in range(ans.bit_length()):
        if ans & (1 << i):
            print(i)
            return
    return


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

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])
    dp = [[0] * w for i in range(h)]
    dp[0][0] = 1 << ab
    for i in range(1, h + w):
        for x in range(min(i, w)):
            y = i - x - 1
            for mx, my in [[0, 1], [1, 0]]:
                mx += x
                my += y
                if 0 <= mx < w and 0 <= my < h:
                    values = dp[y][x]
                    mxy = abs(a[my][mx] - b[my][mx])
                    value = [i for i in range(values.bit_length()) if values & (1 << i)]
                    for v in value:
                        dp[my][mx] |= (1 << abs(v - mxy)) | (1 << (mxy + v))
    ans = dp[-1][-1]
    for i in range(ans.bit_length()):
        if ans & (1 << i):
            print(i)
            return
    return


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

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(int)
    d[(0, 0)] = 1 << ab
    for _ in range(h + w - 2):
        nd = defaultdict(int)
        for key, values in d.items():
            x, y = key
            value = [i for i in range(values.bit_length()) if values & (1 << i)]
            if 0 <= x + 1 < w:
                x1y = abs(a[y][x + 1] - b[y][x + 1])
                for v in value:
                    nd[(x+1, y)] |= 1 << abs(v - x1y)
                    nd[(x+1, y)] |= 1 << 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)] |= 1 << abs(v - xy1)
                    nd[(x, y + 1)] |= 1 << v + xy1
        d = nd
    ans = d[(w - 1, h - 1)]
    for i in range(ans.bit_length()):
        if ans & (1 << i):
            print(i)
            return
    return


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

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(list)
    d[(0, 0)].append(ab)
    for _ in range(h + w - 2):
        nd = defaultdict(list)
        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)].append(abs(v - x1y))
                    nd[(x+1, y)].append(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)].append(abs(v - xy1))
                    nd[(x, y + 1)].append(v + xy1)
        for key in nd.keys():
            nd[key] = list(set(nd[key]))
        d = nd
    print(min(d[(w-1,h-1)]))
    return


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