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: Wrong Answer

Solution code:

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

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

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


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

for i in range(h):
    ndp = [set() for _ in range(w)]
    for j in range(w):
        v = a[i][j] - b[i][j]
        #print(v)
        for c in dp[j]: 
            ndp[j].add(c+v)
            ndp[j].add(c-v)
        if j:
            for c in ndp[j-1]:
                ndp[j].add(c+v)
                ndp[j].add(c-v)

    dp = ndp
    #print(dp)
    

print(min(map(abs, dp[j])))

Submission status: Time Limit Exceeded

Solution code:
def getval():
    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)]
    return h,w,a,b

def main(h,w,a,b):
    dp = []
    for i in range(w):
        dp.append([False for j in range(1+160*(i+1))])

    dp[0][abs(a[0][0]-b[0][0])] = True
    for i in range(w-1):
        cura = a[0][i+1]
        curb = b[0][i+1]
        prev = dp[i]
        for j in range(len(prev)):
            if prev[j]:
                u1 = abs(j-(cura-curb))
                u2 = abs(j-(curb-cura))
                for k in [u1,u2]:
                    if k<=160*80:
                        dp[i+1][k] = True
    #for i in dp:
      #print(i[:20])
    for i in range(h-1):
        temp = []
        for j in range(w):
            cur = [False for k in range(min(1+160*(i+j+2),1+160*80))]
            prev1 = dp[j]
            prev2 = dp[j]
            if temp:
                prev2 = temp[-1]
            cura = a[i+1][j]
            curb = b[i+1][j]
            for k in range(len(prev1)):
                if prev1[k] or prev2[k]:
                    u1 = abs(k-(cura-curb))
                    u2 = abs(k-(curb-cura))
                    for l in [u1,u2]:
                        if l<160*80:
                            cur[l] = True
            temp.append(cur)
        dp = temp
        #for i in dp:
          #print(i[:20])

    ans = 0
    for i in range(160*80+1):
        if dp[-1][i]:
            ans = i 
            break
    print(ans)        

if __name__=="__main__":
    h,w,a,b = getval()
    main(h,w,a,b)

Submission status: Time Limit Exceeded

Solution code:
def getval():
    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)]
    return h,w,a,b

def main(h,w,a,b):
    dp = []
    for i in range(w):
        dp.append([False for j in range(1+160*(i+1))])

    dp[0][abs(a[0][0]-b[0][0])] = True
    for i in range(w-1):
        cura = a[0][i+1]
        curb = b[0][i+1]
        prev = dp[i]
        for j in range(len(prev)):
            if prev[j]:
                u1 = abs(j-(cura-curb))
                u2 = abs(j-(curb-cura))
                for k in [u1,u2]:
                    if k<=160*80:
                        dp[i+1][k] = True
    #for i in dp:
      #print(i[:20])
    for i in range(h-1):
        temp = []
        for j in range(w):
            temp.append([False for k in range(min(1+160*(i+j+2),1+160*80))])
        for j in range(w):
            prev1 = dp[j]
            prev2 = temp[j-1]
            cura = a[i+1][j]
            curb = b[i+1][j]
            for k in range(len(prev1)):
                if prev1[k] or prev2[k]:
                    u1 = abs(k-(cura-curb))
                    u2 = abs(k-(curb-cura))
                    for l in [u1,u2]:
                        if l<160*80:
                            temp[j][l] = True
        dp = temp
        #for i in dp:
          #print(i[:20])

    ans = 0
    for i in range(160*80+1):
        if dp[-1][i]:
            ans = i 
            break
    print(ans)        

if __name__=="__main__":
    h,w,a,b = getval()
    main(h,w,a,b)

Submission status: Time Limit Exceeded

Solution code:
def getval():
    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)]
    return h,w,a,b

def main(h,w,a,b):
    dp = []
    for i in range(w):
        dp.append([False for j in range(1+160*(i+1))])

    dp[0][abs(a[0][0]-b[0][0])] = True
    for i in range(w-1):
        cura = a[0][i+1]
        curb = b[0][i+1]
        prev = dp[i]
        for j in range(len(prev)):
            if prev[j]:
                u1 = abs(j-(cura-curb))
                u2 = abs(j-(curb-cura))
                for k in [u1,u2]:
                    if k<=160*80:
                        dp[i+1][k] = True
    #for i in dp:
      #print(i[:20])
    for i in range(h-1):
        temp = [[False for i in range(160*80+1)] for i in range(w)]
        temp = []
        for j in range(w):
            temp.append([False for k in range(min(1+160*(i+j+2),1+160*80))])
        for j in range(w):
            prev1 = dp[j]
            prev2 = temp[j-1]
            cura = a[i+1][j]
            curb = b[i+1][j]
            for k in range(len(prev1)):
                if prev1[k] or prev2[k]:
                    u1 = abs(k-(cura-curb))
                    u2 = abs(k-(curb-cura))
                    for l in [u1,u2]:
                        if l<160*80:
                            temp[j][l] = True
        dp = temp
        #for i in dp:
          #print(i[:20])

    ans = 0
    for i in range(160*80+1):
        if dp[-1][i]:
            ans = i 
            break
    print(ans)        

if __name__=="__main__":
    h,w,a,b = getval()
    main(h,w,a,b)

Submission status: Time Limit Exceeded

Solution code:
def getval():
    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)]
    return h,w,a,b

def main(h,w,a,b):
    dp = [[False for i in range(160*80+1)] for i in range(w)]
    dp[0][abs(a[0][0]-b[0][0])] = True
    for i in range(w-1):
        cura = a[0][i+1]
        curb = b[0][i+1]
        prev = dp[i]
        for j in range(160*80+1):
            if prev[j]:
                u1 = abs(j-(cura-curb))
                u2 = abs(j-(curb-cura))
                for k in [u1,u2]:
                    if k<=160*80:
                        dp[i+1][k] = True
    #for i in dp:
      #print(i[:20])
    for i in range(h-1):
        temp = [[False for i in range(160*80+1)] for i in range(w)]
        for j in range(w):
            prev1 = dp[j]
            prev2 = temp[j-1]
            cura = a[i+1][j]
            curb = b[i+1][j]
            for k in range(160*80+1):
                if prev1[k] or prev2[k]:
                    u1 = abs(k-(cura-curb))
                    u2 = abs(k-(curb-cura))
                    for l in [u1,u2]:
                        if l<160*80:
                            temp[j][l] = True
        dp = temp
        #for i in dp:
          #print(i[:20])

    ans = 0
    for i in range(160*80+1):
        if dp[-1][i]:
            ans = i 
            break
    print(ans)        

if __name__=="__main__":
    h,w,a,b = getval()
    main(h,w,a,b)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
I=lambda:int(input())
MI=lambda:map(int,input().split())
LI=lambda:list(map(int,input().split()))

H,W=MI()
A=[LI() for _ in [0]*H]
B=[LI() for _ in [0]*H]

M=80*(H+W)
dp=[[[False]*(M+1) for _ in [0]*W] for _ in [0]*H]
dp[0][0][0]=True

m=M
for h in range(H):
    for w in range(W):
        d=A[h][w]-B[h][w]
        for a in range(M+1):
            if dp[h][w][a]:
                #配る
                if h!=H-1:
                    if 0<=abs(a+d)<=M:
                        dp[h+1][w][abs(a+d)]=True
                        if (h+1)*w==(H-1)*(W-1):
                            m=min(abs(a+d),m)
                    if 0<=abs(a-d)<=M:
                        dp[h+1][w][abs(a-d)]=True
                        if (h+1)*w==(H-1)*(W-1):
                            m=min(abs(a-d),m)
                if w!=W-1:
                    if 0<=abs(a+d)<=M:
                        dp[h][w+1][abs(a+d)]=True
                        if h*(w+1)==(H-1)*(W-1):
                            m=min(abs(a+d),m)
                    if 0<=abs(a-d)<=M:
                        dp[h][w+1][abs(a-d)]=True
                        if h*(w+1)==(H-1)*(W-1):
                            m=min(abs(a-d),m)

res=dp[H-1][W-1][:]
for a in range(M+1):
    if dp[H-1][W-1][a]:
        d=A[H-1][W-1]-B[H-1][W-1]
        if 0<=abs(a+d)<=M:
            res[abs(a+d)]=True
            m=min(abs(a+d),m)
        if 0<=abs(a-d)<=M:
            res[abs(a-d)]=True
            m=min(abs(a-d),m)
            
print(m)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
I=lambda:int(input())
MI=lambda:map(int,input().split())
LI=lambda:list(map(int,input().split()))

H,W=MI()
A=[LI() for _ in [0]*H]
B=[LI() for _ in [0]*H]

M=80*(H+W)
dp=[[[False]*(2*M+1) for _ in [0]*W] for _ in [0]*H]
dp[0][0][M]=True

m=2*M+1
for h in range(H):
    for w in range(W):
        d=A[h][w]-B[h][w]
        for a in range(2*M+1):
            if dp[h][w][a]:
                #配る
                if h!=H-1:
                    if 0<=a+d<=2*M:
                        dp[h+1][w][a+d]=True
                        if (h+1)*w==(H-1)*(W-1):
                            m=min(abs(a+d-M),m)
                    if 0<=a-d<=2*M:
                        dp[h+1][w][a-d]=True
                        if (h+1)*w==(H-1)*(W-1):
                            m=min(abs(a-d-M),m)
                if w!=W-1:
                    if 0<=a+d<=2*M:
                        dp[h][w+1][a+d]=True
                        if h*(w+1)==(H-1)*(W-1):
                            m=min(abs(a+d-M),m)
                    if 0<=a-d<=2*M:
                        dp[h][w+1][a-d]=True
                        if h*(w+1)==(H-1)*(W-1):
                            m=min(abs(a-d-M),m)
                            
res=dp[H-1][W-1][:]
for a in range(2*M+1):
    if dp[H-1][W-1][a]:
        d=A[H-1][W-1]-B[H-1][W-1]
        if 0<=a+d<=2*M:
            res[a+d]=True
            m=min(abs(a+d-M),m)
        if 0<=a-d<=2*M:
            res[a-d]=True
            m=min(abs(a+d-M),m)
            
print(m)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
MI=lambda:map(int,input().split())
LI=lambda:list(map(int,input().split()))

H,W=MI()
A,B=[],[]
for _ in [0]*H:
    A.append(LI())
    
for _ in [0]*H:
    B.append(LI())
    
G=[[set() for i in range(W)] for j in range(H)]
dif=A[0][0]-B[0][0]
G[0][0].add(0)

M=-1
for h in range(H):
    for w in range(W):
        d=A[h][w]-B[h][w]
        M=max(M,abs(d))

M*=(H+W)
res=[[[False]*(2*M+1) for _ in [0]*W] for _ in [0]*H]

for h in range(H):
    for w in range(W):
        d=A[h][w]-B[h][w]
        for a in G[h][w]:
            if h!=H-1:
                G[h+1][w].add(a+d)
                G[h+1][w].add(a-d)
            if w!=W-1:
                G[h][w+1].add(a+d)
                G[h][w+1].add(a-d)
    
res=set()
for a in G[H-1][W-1]:
    res.add(a)
d=A[H-1][W-1]-B[H-1][W-1]
for a in G[H-1][W-1]:
    res.add(a+d)
    res.add(a-d)

res=list(res)
res1=sorted([-r for r in res if r<=0])
res2=sorted([r for r in res if r>=0])
print(min(res1[0],res2[0]))

# for h in range(H):
#     for w in range(W):
#         print(list(G[h][w]))

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


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 = [[set() for _ in range(W)] for _ in range(H)]
    dp[0][0] = {A[0][0] - B[0][0], B[0][0] - A[0][0]}
    for h in range(H):
        for w in range(W):
            a, b = A[h][w], B[h][w]
            if w - 1 >= 0:
                for num in dp[h][w - 1]:
                    dp[h][w].add(num + a - b)
                    dp[h][w].add(num + b - a)
            if h - 1 >= 0:
                for num in dp[h - 1][w]:
                    dp[h][w].add(num + a - b)
                    dp[h][w].add(num + b - a)

    res = f_inf
    for num in dp[-1][-1]:
        res = min(res, abs(num))
    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Time Limit Exceeded

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    H, W = map(int, readline().split())
    A = [list(map(int, readline().split())) for _ in range(H)]
    B = [list(map(int, readline().split())) for _ in range(H)]

    G = [[0] * W for _ in range(H)]
    M = 0
    for i in range(H):
        for j in range(W):
            G[i][j] = abs(A[i][j] - B[i][j])
            if M < G[i][j]:
                M = G[i][j]

    L = (H + W) * M
    dp = [[[False] * (L + 1) for j in range(W + 1)] for i in range(H + 1)]
    dp[0][1][0] = dp[1][0][0] = True

    for i in range(H):
        for j in range(W):
            b = G[i][j]
            for k in range(L + 1):
                if abs(k + b) <= L:
                    dp[i + 1][j + 1][k] = (
                        dp[i][j + 1][abs(k - b)]
                        or dp[i][j + 1][abs(k + b)]
                        or dp[i + 1][j][abs(k - b)]
                        or dp[i + 1][j][abs(k + b)]
                    )
                else:
                    dp[i + 1][j + 1][k] = dp[i][j + 1][abs(k - b)] or dp[i + 1][j][abs(k - b)]

    ans = INF
    for k in range(L + 1):
        if dp[H][W][k]:
            ans = k
            break

    print(ans)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
H,W=map(int,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=[[0 for j in range(W)] for i in range(H)]
dp[0][0]=1<<abs(A[0][0]-B[0][0])
M=80*80*2
for i in range(H):
    for j in range(W):
        dij=A[i][j]-B[i][j]
        if i>0:
            for x in range(M):
                if (1<<x)&dp[i-1][j]==0:
                    continue
                dp[i][j]|=1<<abs(x+dij)
                dp[i][j]|=1<<abs(x-dij)
        if j>0:
            for y in range(M):
                if (1<<y)&dp[i][j-1]==0:
                    continue
                dp[i][j]|=1<<abs(y+dij)
                dp[i][j]|=1<<abs(y-dij)
for i in range(M):
    if (1<<i)&dp[-1][-1]!=0:
        print(i)
        break

Submission status: Time Limit Exceeded

Solution code:
H,W=map(int,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)]
dp[0][0].add(abs(A[0][0]-B[0][0]))
for i in range(H):
    for j in range(W):
        dij=A[i][j]-B[i][j]
        if i>0:
            for x in dp[i-1][j]:
                dp[i][j].add(abs(x+dij))
                dp[i][j].add(abs(x-dij))
        if j>0:
            for y in dp[i][j-1]:
                dp[i][j].add(abs(y+dij))
                dp[i][j].add(abs(y-dij))
print(min(dp[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
H,W=map(int,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)]
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):
        dij=A[i][j]-B[i][j]
        if i>0:
            for x in dp[i-1][j]:
                dp[i][j].add(x+dij)
                dp[i][j].add(x-dij)
        if j>0:
            for y in dp[i][j-1]:
                dp[i][j].add(y+dij)
                dp[i][j].add(y-dij)
ans=10**10
for i in dp[-1][-1]:
    if abs(i)<ans:
        ans=abs(i)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq

h,w = ma()
A = []
for i in range(h):
    A.append(lma())
B= []
for i in range(h):
    B.append(lma())
D = [[abs(A[i][j]-B[i][j]) for j in range(w)] for i in range(h)]
mx = 0
for i in range(h):
    for j in range(w):
        mx = max(mx,D[i][j])
prev = [[False]*((h+w)*mx+1) for j in range(w)]
nex = [[False]*((h+w)*mx+1) for j in range(w)]
prev[0][0]=True
for i in range(h):
    for j in range(w):
        d = D[i][j]
        if j==0:
            for k in range((h+w)*mx+1-d):
                nex[j][k+d] = nex[j][k+d] or prev[j][k]
                nex[j][abs(k-d)] = nex[j][abs(k-d)] or prev[j][k]
        else:
            for k in range((h+w)*mx+1-d):
                nex[j][k+d] = nex[j][k+d] or prev[j][k] or nex[j-1][k]
                nex[j][abs(k-d)] = nex[j][abs(k-d)] or prev[j][k] or nex[j-1][k]
    prev=nex
    nex=[[False]*((h+w)*mx+1) for j in range(w)]
for i in range((h+w)*mx+1):
    if prev[w-1][i]:
        print(i)
        exit()

Submission status: Time Limit Exceeded

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq

h,w = ma()
A = []
for i in range(h):
    A.append(lma())
B= []
for i in range(h):
    B.append(lma())
D = [[abs(A[i][j]-B[i][j]) for j in range(w)] for i in range(h)]
prev = [[False]*(2*80*w+1) for j in range(w)]
nex = [[False]*(2*80*w+1) for j in range(w)]
prev[0][0]=True
for i in range(h):
    for j in range(w):
        d = D[i][j]
        if j==0:
            for k in range(2*80*w+1-d):
                nex[j][k+d] = nex[j][k+d] or prev[j][k]
                nex[j][abs(k-d)] = nex[j][abs(k-d)] or prev[j][k]
        else:
            for k in range(2*80*w+1-d):
                nex[j][k+d] = nex[j][k+d] or prev[j][k] or nex[j-1][k]
                nex[j][abs(k-d)] = nex[j][abs(k-d)] or prev[j][k] or nex[j-1][k]
    prev=nex
    nex=[[False]*(2*80*w+1) for j in range(w)]
for i in range(2*80*w+1):
    if prev[w-1][i]:
        print(i)
        exit()

Submission status: Time Limit Exceeded

Solution code:
import copy
H, W = map(int, input().split())
k_max = 80 * (H + W - 1)
ans = k_max
grid = []

for i in range(H):
  grid.append(list(map(int, input().split())))
for i in range(H):
  for j, var in enumerate(list(map(int, input().split()))):
    grid[i][j] = abs(grid[i][j] - var)
  
dp = [[[False] * H for _ in range(W)] for _ in range(k_max)]
dp[grid[0][0]][0][0] = True

def change_dp(k, w, h):
  global dp
  global grid
  global ans
  if w != W-1:
    d = grid[h][w+1]
    dp[k+d][w+1][h] = True
    dp[abs(k-d)][w+1][h] = True
    if w + 1 == W - 1 and h == H - 1:
      ans = min(ans, k+d, abs(k-d))
    change_dp(k+d,w+1,h)
    change_dp(abs(k-d),w+1,h)
  if h != H-1:
    d = grid[h+1][w]
    dp[k+d][w][h+1] = True
    dp[abs(k-d)][w][h+1] = True
    if w == W - 1 and h + 1 == H - 1:
      ans = min(ans, k+d, abs(k-d))
    change_dp(k+d,w,h+1)
    change_dp(abs(k-d),w,h+1)
  
change_dp(grid[0][0],0,0)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
from collections import Counter
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

import sys
import itertools
# import numpy as np
import time
import math
from heapq import heappop, heappush
from collections import defaultdict
from collections import Counter
from collections import deque
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())
H, W = map(int, input().split())
A = [0] * H
for i in range(H):
    A[i] = list(map(int, input().split()))
B = [0] * H
for i in range(H):
    B[i] = list(map(int, input().split()))

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

MAX = H * W
dp = [[[INF] * W for _ in range(H)] for _ in range(MAX)]
for k in range(MAX):
    for i in range(H):
        for j in range(W):
            if k == 0:
                if i == 0 and j == 0:
                    dp[k][i][j] = C[i][j]
                elif i == 0:
                    dp[k][i][j] = dp[k][i][j - 1] + C[i][j]
                elif j == 0:
                    dp[k][i][j] = dp[k][i - 1][j] + C[i][j]
                else:
                    dp[k][i][j] = min(dp[k][i - 1][j], dp[k][i][j - 1]) + C[i][j]
            else:
                if i == 0 and j == 0:
                    continue
                elif i == 0:
                    dp[k][i][j] = min(abs(dp[k - 1][i][j - 1] - C[i][j]), dp[k][i][j])
                elif j == 0:
                    dp[k][i][j] = min(abs(dp[k - 1][i - 1][j] - C[i][j]), dp[k][i][j])
                else:
                    dp[k][i][j] = min(abs(dp[k - 1][i - 1][j] - C[i][j]), \
                        abs(dp[k - 1][i][j - 1] - C[i][j]), dp[k][i][j])

ans = INF
for k in range(MAX):
    val = dp[k][H - 1][W - 1]
    ans = min(ans, val)
print(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)]
diffs = [[abs(A[i][j] - B[i][j]) for j in range(W)] for i in range(H)]
max_diff = 0
for diff in diffs:
    max_diff = max(max_diff, max(diff))
r_k = max_diff*(H+W)+1
dp = [[[False] * r_k for _ in range(W)] for _ in range(H)]
dp[0][0][0] = True
for i in range(H):
    for j in range(W):
        diff = diffs[i][j]
        dp_ = dp[i][j]
        if j < W-1:
            dpj = dp[i][j + 1]
            for k in range(r_k):
                if dp_[k] == True:
                    dpj[k + diff] = True
                    dpj[abs(k-diff)] = True
        if i < H - 1:
            dpi = dp[i + 1][j]
            for k in range(r_k):
                if dp_[k] == True:
                    dpi[k + diff] = True
                    dpi[abs(k-diff)] = True

ans = pow(80, 3)
diff = diffs[H-1][W-1]
for k, flg in enumerate(dp[H - 1][W - 1]):
    if flg:
        ans = min(ans, abs(k-diff), k+diff)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)
# INF =  float("inf")
INF = 10**18
import bisect
import statistics
mod = 10**9+7
# mod = 998244353

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

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

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

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

dp = [[set() for j in range(W+1)] for i in range(H+1)]
dp[0][1] = set([0])
dp[1][0] = set([0])
for i in range(1,H+1):
    for j in range(1,W+1):
        for k in list(dp[i-1][j]):
            if k + C[i][j] <= 6400 and k + C[i][j] >= -6400:
                dp[i][j].add(k + C[i][j])
            if k - C[i][j] <= 6400 and k - C[i][j] >= -6400:
                dp[i][j].add(k - C[i][j])
        for k in list(dp[i][j-1]):
            if k + C[i][j] <= 6400 and k + C[i][j] >= -6400:
                dp[i][j].add(k + C[i][j])
            if k - C[i][j] <= 6400 and k - C[i][j] >= -6400:
                dp[i][j].add(k - C[i][j])

ans = list(dp[H][W])
ans = [abs(i) for i in ans]
print(sorted(ans)[0])

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)
# INF =  float("inf")
INF = 10**18
import bisect
import statistics
mod = 10**9+7
# mod = 998244353

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

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

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

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

dp = [[set() for j in range(W+1)] for i in range(H+1)]
dp[0][1] = set([0])
dp[1][0] = set([0])
for i in range(1,H+1):
    for j in range(1,W+1):
        for k in list(dp[i-1][j]):
            dp[i][j].add(k + C[i][j])
            dp[i][j].add(k - C[i][j])
        for k in list(dp[i][j-1]):
            dp[i][j].add(k + C[i][j])
            dp[i][j].add(k - C[i][j])

ans = list(dp[H][W])
ans = [abs(i) for i in ans]
print(sorted(ans)[0])

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())
A = []
for _ in range(h):
    a = list(map(int,input().split()))
    A.append(a)
B = []
for _ in range(h):
    b = list(map(int,input().split()))
    B.append(b)
g = [[0]*(w+1) for _ in range(h+1)]
m = 0
for i in range(1,h+1):
    for j in range(1,w+1):
        g[i][j] = abs(A[i-1][j-1]-B[i-1][j-1])
m  = 80*(h+w-1)//2
dp = [[[False for _ in range(m+1)] for _ in range(w+1)] for _ in range(h+1)]
dp[1][1][g[1][1]] = True

for i in range(1,h+1):
    for j in range(1,w+1):
        for k in range(m+1):
            if k + g[i][j]<m:
                dp[i][j][k] = dp[i][j][k] or dp[i-1][j][abs(k-g[i][j])] or dp[i-1][j][k+g[i][j]] or dp[i][j-1][abs(k-g[i][j])] or dp[i][j-1][k+g[i][j]]
            else:
                dp[i][j][k] = dp[i][j][k] or dp[i-1][j][abs(k-g[i][j])] or dp[i][j-1][abs(k-g[i][j])]
            

for k in range(m+1):
    if dp[-1][-1][k]:
        print(k);exit()

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())
A = []
for _ in range(h):
    a = list(map(int,input().split()))
    A.append(a)
B = []
for _ in range(h):
    b = list(map(int,input().split()))
    B.append(b)
g = [[0]*(w+1) for _ in range(h+1)]
m = 0
for i in range(1,h+1):
    for j in range(1,w+1):
        m = max(m,abs(A[i-1][j-1]-B[i-1][j-1]))
        g[i][j] = abs(A[i-1][j-1]-B[i-1][j-1])
m *= (h+w)//2
dp = [[[False for _ in range(m+1)] for _ in range(w+1)] for _ in range(h+1)]
dp[1][1][g[1][1]] = True

for i in range(1,h+1):
    for j in range(1,w+1):
        for k in range(m+1):
            if k + g[i][j]<m:
                dp[i][j][k] = dp[i][j][k] or dp[i-1][j][abs(k-g[i][j])] or dp[i-1][j][k+g[i][j]] or dp[i][j-1][abs(k-g[i][j])] or dp[i][j-1][k+g[i][j]]
            else:
                dp[i][j][k] = dp[i][j][k] or dp[i-1][j][abs(k-g[i][j])] or dp[i][j-1][abs(k-g[i][j])]
            

for k in range(m+1):
    if dp[-1][-1][k]:
        print(k);exit()

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())
A = []
for _ in range(h):
    a = list(map(int,input().split()))
    A.append(a)
B = []
for _ in range(h):
    b = list(map(int,input().split()))
    B.append(b)
g = [[0]*(w+1) for _ in range(h+1)]
m = 0
for i in range(1,h+1):
    for j in range(1,w+1):
        m = max(m,abs(A[i-1][j-1]-B[i-1][j-1]))
        g[i][j] = abs(A[i-1][j-1]-B[i-1][j-1])
m *= (h+w)
dp = [[[False for _ in range(m+1)] for _ in range(w+1)] for _ in range(h+1)]
dp[1][1][g[1][1]] = True

for i in range(1,h+1):
    for j in range(1,w+1):
        for k in range(m+1):
            if k + g[i][j]<m:
                dp[i][j][k] = dp[i][j][k] or dp[i-1][j][abs(k-g[i][j])] or dp[i-1][j][k+g[i][j]] or dp[i][j-1][abs(k-g[i][j])] or dp[i][j-1][k+g[i][j]]
            else:
                dp[i][j][k] = dp[i][j][k] or dp[i-1][j][abs(k-g[i][j])] or dp[i][j-1][abs(k-g[i][j])]
            

for k in range(m+1):
    if dp[-1][-1][k]:
        print(k);exit()

Submission status: Time Limit Exceeded

Solution code:

def resolve():
    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)]

    # 移動直前の偏りをkとし、移動先のマス(i, j)
    # についてd = abs(A[i][j] - B[i][j])
    # とした際に、移動後の偏りをabs(k - d)
    # とするかabs(k + d)とするか」を考えることと同値である。
    # dp[i][j][k] : マス (i, j) までの経路の偏りが k になることがあるか？
    max_k = 160 * 80
    dp = [[[False] * (max_k + 1) for _ in range(W + 1)] for _ in range(H + 1)]

    dp[0][1][0] = True
    dp[1][0][0] = True

    for i in range(H):
        for j in range(W):
            for k in range(max_k + 1):
                d = abs(A[i][j] - B[i][j])
                # i+1移動
                if k + d <= max_k:
                    dp[i + 1][j + 1][k + d] |= dp[i + 1][j][k]
                if abs(k - d) <= max_k:
                    dp[i + 1][j + 1][abs(k - d)] |= dp[i + 1][j][k]
                # j+1移動
                if k + d <= max_k:
                    dp[i + 1][j + 1][k + d] |= dp[i][j + 1][k]
                if abs(k - d) <= max_k:
                    dp[i + 1][j + 1][abs(k - d)] |= dp[i][j + 1][k]

    for k in range(max_k + 1):
        if dp[H][W][k]:
            return print(k)


if __name__ == "__main__":
    resolve()