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:
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)]
M = 0

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

ZZZ = M*(H+W-1)+1

DP = [[[0]*ZZZ for i in range(W)] for j in range(H)]

for h in range(H):
    for w in range(W):
        if h==0 and w==0:
            DP[h][w][C[h][w]] = 1
        elif h==0:
            for i in range(ZZZ):
                DP[h][w][i] = DP[h][w-1][abs(i-C[h][w])]| (DP[h][w-1][abs(i+C[h][w])] if abs(i+C[h][w])<ZZZ else 0)
        elif w==0:
            for i in range(ZZZ):
                DP[h][w][i] = DP[h-1][w][abs(i-C[h][w])]|(DP[h-1][w][abs(i+C[h][w])] if abs(i+C[h][w])<ZZZ else 0)
        else:
            for i in range(ZZZ):
                DP[h][w][i] = DP[h-1][w][abs(i-C[h][w])]|(DP[h-1][w][abs(i+C[h][w])] if abs(i+C[h][w])<ZZZ else 0)|DP[h][w-1][abs(i-C[h][w])]|(DP[h][w-1][abs(i+C[h][w])] if abs(i+C[h][w])<ZZZ else 0)
                
for i in range(ZZZ):
    if DP[H-1][W-1][i]==1:
        ans = i
        break
print(ans)

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

for h in range(H):
    for w in range(W):
        C[h][w] = abs(A[h][w] - B[h][w])
        
#print(C)

ZZZ = 80*77

DP = [[[0]*ZZZ for i in range(W)] for j in range(H)]

for h in range(H):
    for w in range(W):
        if h==0 and w==0:
            DP[h][w][C[h][w]] = 1
        elif h==0:
            for i in range(ZZZ):
                DP[h][w][i] = DP[h][w-1][abs(i-C[h][w])]| (DP[h][w-1][abs(i+C[h][w])] if abs(i+C[h][w])<ZZZ else 0)
        elif w==0:
            for i in range(ZZZ):
                DP[h][w][i] = DP[h-1][w][abs(i-C[h][w])]|(DP[h-1][w][abs(i+C[h][w])] if abs(i+C[h][w])<ZZZ else 0)
        else:
            for i in range(ZZZ):
                DP[h][w][i] = DP[h-1][w][abs(i-C[h][w])]|(DP[h-1][w][abs(i+C[h][w])] if abs(i+C[h][w])<ZZZ else 0)|DP[h][w-1][abs(i-C[h][w])]|(DP[h][w-1][abs(i+C[h][w])] if abs(i+C[h][w])<ZZZ else 0)
                
for i in range(ZZZ):
    if DP[H-1][W-1][i]==1:
        ans = i
        break
print(ans)

Submission status: Time Limit Exceeded

Solution code:

import sys
from collections import defaultdict
from collections import deque
import numpy as np
import heapq
from heapq import heappush, heappop
import itertools
import math
import copy


#read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 7)

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

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

for _ in range(H):
    b = list(map(int, input().split()))
    B.append(b)

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

    C.append(cs)


def calc(arr):
    # print(arr)
    arr.sort(reverse=True)
    a = 0
    b = 0

    for i in range(len(arr)):
        if a > b:
            b += arr[i]
        else:
            a += arr[i]

    return abs(a-b)


def dfs(x, y, arr):
    # print(arr)
    arr.append(C[y][x])

    if x == W-1 and y == H-1:
        return calc(arr)

    xs = [0, 1]
    ys = [1, 0]

    mn = 10**4
    for i in range(2):
        if x+xs[i] <= W-1 and y+ys[i] <= H-1:
            arr2 = copy.copy(arr)
            a = dfs(x+xs[i], y+ys[i], arr2)

            if a < mn:
                mn = a

    return mn


ans = dfs(0, 0, [])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H, W=map(int, input().split())
A=[list(map(int, input().split())) for i in range(H)]
B=[list(map(int, input().split())) for i in range(H)]
AB=[[abs(A[i][j]-B[i][j]) for j in range(W)] for i in range(H)]

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

for i in range(1, W):
  ks=G[0][i-1]
  for k in ks:
    G[0][i].add(abs(k+AB[0][i]))
    G[0][i].add(abs(k-AB[0][i]))

for i in range(1, H):
  ks=G[i-1][0]
  for k in ks:
    G[i][0].add(abs(k+AB[i][0]))
    G[i][0].add(abs(k-AB[i][0]))

from collections import deque

def f(data):
  i=data[0]
  j=data[1]
  tmp=AB[i][j]
  
  ks=G[i-1][j]
  for k in ks:
    G[i][j].add(abs(k+tmp))
    G[i][j].add(abs(k-tmp))
    
  ks=G[i][j-1]
  for k in ks:
    G[i][j].add(abs(k+tmp))
    G[i][j].add(abs(k-tmp))
    
  if i<H-1:
    q.append([i+1, j])
  if j<W-1:
    q.append([i, j+1])
    
q=deque()
q.append([1, 1])
while len(q)>0:
  data=q.popleft()
  f(data)
  
print(min(G[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
H, W=map(int, input().split())
A=[list(map(int, input().split())) for i in range(H)]
B=[list(map(int, input().split())) for i in range(H)]
AB=[[abs(A[i][j]-B[i][j]) for j in range(W)] for i in range(H)]

from collections import defaultdict
G=[[defaultdict(int) for j in range(W)] for i in range(H)]
G[0][0][AB[0][0]]+=1

for i in range(1, W):
  ks=G[0][i-1].keys()
  for k in ks:
    G[0][i][abs(k+AB[0][i])]+=1
    G[0][i][abs(k-AB[0][i])]+=1
    
for i in range(1, H):
  ks=G[i-1][0].keys()
  for k in ks:
    G[i][0][abs(k+AB[i][0])]+=1
    G[i][0][abs(k-AB[i][0])]+=1

from collections import deque

def f(data):
  i=data[0]
  j=data[1]
  tmp=AB[i][j]
  
  ks=G[i-1][j].keys()
  for k in ks:
    G[i][j][abs(k+tmp)]+=1
    G[i][j][abs(k-tmp)]+=1
    
  ks=G[i][j-1].keys()
  for k in ks:
    G[i][j][abs(k+tmp)]+=1
    G[i][j][abs(k-tmp)]+=1
    
  if i<H-1:
    q.append([i+1, j])
  if j<W-1:
    q.append([i, j+1])
    
q=deque()
q.append([1, 1])
while len(q)>0:
  data=q.popleft()
  f(data)
  
print(min(G[-1][-1].keys()))

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

d = [[set() for i in range(w)]for j in range(h)]

d[0][0].add(c[0][0])
d[0][0].add(-c[0][0])

for i in range(h):
    for j in range(w):
        if 0<=i-1<h:
            for x in d[i-1][j]:
                d[i][j].add(abs(x+c[i][j]))
                d[i][j].add(abs(x-c[i][j]))
        if 0<=j-1<w:
            for x in d[i][j-1]:
                d[i][j].add(abs(x+c[i][j]))
                d[i][j].add(abs(x-c[i][j]))

print(min(d[-1][-1]))

Submission status: Time Limit Exceeded

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

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

    N = (H+W) * 80
    dp = [[[False for _ in range(N)] for _ in range(W+1)] for _ in range(H+1)]
    dp[0][0][d[0][0]] = True
    for i in range(H):
        for j in range(W):
            for k in range(N):
                if not dp[i][j][k]:
                    continue

                dp[i+1][j][k+d[i+1][j]] = True
                dp[i+1][j][abs(k - d[i+1][j])] = True
                dp[i][j+1][k+d[i][j+1]] = True
                dp[i][j+1][abs(k - d[i][j+1])] = True

    for i in range(N):
        if dp[H-1][W-1][i]:
            print(i)
            exit()


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
'''input
2 2
1 2
3 4
3 4
2 1
'''
# A coding delight
from sys import stdin, stdout
import gc
from copy import deepcopy
# gc.disable()
input = stdin.readline


def make(f, s, t):
	return str(f) + ' ' + str(s) + ' ' + str(t)


def brute(dp, i, j, s):
	if i == n - 1 and j == m or i == n  and m == j - 1:
		return s
	if i == n or j == m:
		return float('inf')
	if make(i, j, s) in dp:
		return dp[make(i, j, s)]
	
	first = abs(brute(dp, i, j + 1, s + K[i][j]))
	second = abs(brute(dp, i, j + 1, s - K[i][j]))
	third =  abs(brute(dp, i + 1, j , s + K[i][j]))
	fourth = abs(brute(dp, i + 1, j, s - K[i][j]))
	dp[make(i, j, s)] = min(first, second, third, fourth)
	return min(first, second, third, fourth)


	
# main starts
n, m = list(map(int, input().split()))
A = []
for i in range(n):
	A.append(list(map(int, input().split())))
B = []
for i in range(n):
	B.append(list(map(int, input().split())))
K = []
for i in range(n):
	temp = []
	for j in range(m):
		temp.append(abs(A[i][j] - B[i][j]))
	K.append(temp)
dp = dict()
print(brute(dp, 0, 0, 0))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

import sys
from pprint import pprint
sys.setrecursionlimit(300000)


def solve(H: int, W: int, A: "List[List[int]]", B: "List[List[int]]"):
    diffs = [[0] * (W + 1) for _ in range(H + 1)]
    for i in range(H):
        for j in range(W):
            diffs[i][j] = abs(A[i][j] - B[i][j])
    dp = [[set() for _ in range(W + 1)] for _ in range(H + 1)]
    dp[0][0].add(diffs[0][0])
    for i in range(H):
        for j in range(W):
            tmp = dp[i][j]
            for val in tmp:
                dp[i + 1][j].add(abs(val + diffs[i + 1][j]))
                dp[i + 1][j].add(abs(val - diffs[i + 1][j]))
                dp[i][j + 1].add(abs(val + diffs[i][j + 1]))
                dp[i][j + 1].add(abs(val - diffs[i][j + 1]))
    ret = min(dp[H - 1][W - 1])
    print(ret)
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    A = [[int(next(tokens)) for _ in range(W)] for _ in range(H)]  # type: "List[List[int]]"
    B = [[int(next(tokens)) for _ in range(W)] for _ in range(H)]  # type: "List[List[int]]"
    solve(H, W, A, B)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

import sys
from pprint import pprint
sys.setrecursionlimit(300000)


def solve(H: int, W: int, A: "List[List[int]]", B: "List[List[int]]"):
    diffs = [[0] * (W + 1) for _ in range(H + 1)]
    for i in range(H):
        for j in range(W):
            diffs[i][j] = abs(A[i][j] - B[i][j])
    dp = [[[] for _ in range(W + 1)] for _ in range(H + 1)]
    dp[0][0].append(diffs[0][0])
    for i in range(H):
        for j in range(W):
            tmp = dp[i][j]
            for val in tmp:
                dp[i + 1][j].append(abs(val + diffs[i + 1][j]))
                dp[i + 1][j].append(abs(val - diffs[i + 1][j]))
                dp[i][j + 1].append(abs(val + diffs[i][j + 1]))
                dp[i][j + 1].append(abs(val - diffs[i][j + 1]))
    ret = min(dp[H - 1][W - 1])
    print(ret)
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    A = [[int(next(tokens)) for _ in range(W)] for _ in range(H)]  # type: "List[List[int]]"
    B = [[int(next(tokens)) for _ in range(W)] for _ in range(H)]  # type: "List[List[int]]"
    solve(H, W, A, B)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from fractions import gcd
# from datetime import date, timedelta
from heapq import*
import math
from collections import defaultdict, Counter, deque
from bisect import *
import itertools
import fractions
# import sys
# sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
# input = sys.stdin.readline


def main():
    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 = [[[False for i in range(16001)]
           for j in range(w + 1)] for i in range(h + 1)]

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


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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
A=[]
x=[0]*(W+2)
A.append(x)
for i in range(H):
    a=list(map(int,input().split()))
    A.append([0]+a+[0])
A.append(x)
#print(A)

for i in range(H):
    b=list(map(int,input().split()))
    for j in range(W):
        A[i+1][j+1] = abs(A[i+1][j+1]-b[j])
        
#print(A)

L=[[set() for i in range(W+2)] for j in range(H+2)]
L[1][1].add(abs(A[1][1]))
#print(L)
#print(L[0][0])
for i in range(1,H+1):
    for j in range(1,W+1):
        #L[i][j]=list(L[i][j])
        for x in L[i][j]:
            if abs(x+A[i][j+1])<=6400:
                L[i][j+1].add(abs(x+A[i][j+1]))
            if abs(x-A[i][j+1])<=6400:
                L[i][j+1].add(abs(x-A[i][j+1]))
            if abs(x+A[i+1][j])<=6400:
                L[i+1][j].add(abs(x+A[i+1][j]))
            if abs(x-A[i+1][j])<=6400:
                L[i+1][j].add(abs(x-A[i+1][j]))
#print(L)

ans=10**5
L[H][W]=list(L[H][W])
for k in L[H][W]:
    if k<ans:
        ans=k
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
A=[]
x=[0]*(W+2)
A.append(x)
for i in range(H):
    a=list(map(int,input().split()))
    A.append([0]+a+[0])
A.append(x)
#print(A)

for i in range(H):
    b=list(map(int,input().split()))
    for j in range(W):
        A[i+1][j+1] = abs(A[i+1][j+1]-b[j])
        
#print(A)

L=[[set() for i in range(W+2)] for j in range(H+2)]
L[1][1].add(abs(A[1][1]))
#print(L)
#print(L[0][0])
for i in range(1,H+1):
    for j in range(1,W+1):
        L[i][j]=list(L[i][j])
        for x in L[i][j]:
            L[i][j+1].add(abs(x+A[i][j+1]))
            L[i][j+1].add(abs(x-A[i][j+1]))
            L[i+1][j].add(abs(x+A[i+1][j]))
            L[i+1][j].add(abs(x-A[i+1][j]))
#print(L)

ans=10**5
L[H][W]=list(L[H][W])
for k in L[H][W]:
    if k<ans:
        ans=k
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
A=[]
x=[0]*(W+2)
A.append(x)
for i in range(H):
    a=list(map(int,input().split()))
    A.append([0]+a+[0])
A.append(x)
#print(A)

for i in range(H):
    b=list(map(int,input().split()))
    for j in range(W):
        A[i+1][j+1] = abs(A[i+1][j+1]-b[j])
        
#print(A)

L=[[{} for i in range(W+2)] for j in range(H+2)]
L[1][1][A[1][1]]=1
L[1][1][-A[1][1]]=1
#print(L)
#print(L[0][0])
for i in range(1,H+1):
    for j in range(1,W+1):
        for x,y in L[i][j].items():
            #print(x+A[i][j+1])
            if abs(x+A[i][j+1]) not in L[i][j+1] and abs(x+A[i][j+1])<=6400:
                L[i][j+1][abs(x+A[i][j+1])]=1
            if abs(x-A[i][j+1]) not in L[i][j+1] and abs(x-A[i][j+1])<=6400:
                L[i][j+1][abs(x-A[i][j+1])]=1
            if abs(x+A[i+1][j]) not in L[i+1][j] and abs(x+A[i+1][j])<=6400:
                L[i+1][j][abs(x+A[i+1][j])]=1
            if abs(x-A[i+1][j]) not in L[i+1][j] and abs(x-A[i+1][j])<=6400:
                L[i+1][j][abs(x-A[i+1][j])]=1
#print(L)

ans=10**5
for k,v in L[H][W].items():
    if abs(k)<ans:
        ans=abs(k)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
A=[]
x=[0]*(W+2)
A.append(x)
for i in range(H):
    a=list(map(int,input().split()))
    A.append([0]+a+[0])
A.append(x)
#print(A)

for i in range(H):
    b=list(map(int,input().split()))
    for j in range(W):
        A[i+1][j+1] = abs(A[i+1][j+1]-b[j])
        
#print(A)

L=[[{} for i in range(W+2)] for j in range(H+2)]
L[1][1][A[1][1]]=1
L[1][1][-A[1][1]]=1
#print(L)
#print(L[0][0])
for i in range(1,H+1):
    for j in range(1,W+1):
        for x,y in L[i][j].items():
            #print(x+A[i][j+1])
            if abs(x+A[i][j+1]) not in L[i][j+1]:
                L[i][j+1][abs(x+A[i][j+1])]=1
            if abs(x-A[i][j+1]) not in L[i][j+1]:
                L[i][j+1][abs(x-A[i][j+1])]=1
            if abs(x+A[i+1][j]) not in L[i+1][j]:
                L[i+1][j][abs(x+A[i+1][j])]=1
            if abs(x-A[i+1][j]) not in L[i+1][j]:
                L[i+1][j][abs(x-A[i+1][j])]=1
#print(L)

ans=10**5
for k,v in L[H][W].items():
    if abs(k)<ans:
        ans=abs(k)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def ints():
  return [int(x) for x in input().split()]
def readi():
  return int(input())

H, W = ints()
A = [ints() for _ in range(H)]
B = [ints() for _ in range(H)]
D = [[abs(A[h][w]-B[h][w]) for w in range(W)] for h in range(H)]

memo = {}

memo[(0, 0)] = {D[0][0]}

for h in range(H):
  for w in range(W):
    if h==0 and w==0:
      continue 

    d = D[h][w]
    ss = set()
    if h>0:
      s = memo[(h-1, w)]
      ss |= { x+d for x in s }
      ss |= { abs(x-d) for x in s }
    if w>0:
      s = memo[(h, w-1)]
      ss |= { x+d for x in s }
      ss |= { abs(x-d) for x in s }

    memo[(h, w)] = ss

print(min(memo[(H-1, W-1)]))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")


def solve(H: int, W: int, A: "List[List[int]]", B: "List[List[int]]"):
    base = [[None]*W for _ in range(H)]
    for h in range(H):
        for w in range(W):
            base[h][w] = abs(A[h][w]-B[h][w])

    table = [[0 for _ in range(W)] for _ in range(H)]
    table[0][0] |= (1 << base[0][0])
    for h in range(H):
        for w in range(W):
            if h > 0:
                for i in range(6401):
                    j = (table[h-1][w] >> i) & 1
                    if j == 0:
                        continue
                    if base[h][w]+i < 6401:
                        table[h][w] |= 1 << abs(i+base[h][w])
                    table[h][w] |= 1 << abs(i-base[h][w])
            if w > 0:
                for i in range(6401):
                    j = (table[h][w-1] >> i) & 1
                    if j == 0:
                        continue
                    if base[h][w]+i < 6401:
                        table[h][w] |= 1 << abs(i+base[h][w])
                    table[h][w] |= 1 << abs(i-base[h][w])
    for j in range(6401):
        i = (table[H-1][W-1] >> j) & 1
        if i == 1:
            print(j)
            return

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    A = [[int(next(tokens)) for _ in range(W)]
         for _ in range(H)]  # type: "List[List[int]]"
    B = [[int(next(tokens)) for _ in range(W)]
         for _ in range(H)]  # type: "List[List[int]]"
    solve(H, W, A, B)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")


def solve(H: int, W: int, A: "List[List[int]]", B: "List[List[int]]"):
    base = [[None]*W for _ in range(H)]
    for h in range(H):
        for w in range(W):
            base[h][w] = A[h][w]-B[h][w]

    table = [[set() for _ in range(W)] for _ in range(H)]
    table[0][0].add(base[0][0])
    for h in range(H):
        for w in range(W):
            if h > 0:
                for i in table[h-1][w]:
                    if base[h][w]+i < 160*80:
                        table[h][w].add(abs(i+base[h][w]))
                    table[h][w].add(abs(i-base[h][w]))
            if w > 0:
                for i in table[h][w-1]:
                    if base[h][w]+i < 160*80:
                        table[h][w].add(abs(i+base[h][w]))
                    table[h][w].add(abs(i-base[h][w]))
    print(min(table[H-1][W-1]))

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    A = [[int(next(tokens)) for _ in range(W)]
         for _ in range(H)]  # type: "List[List[int]]"
    B = [[int(next(tokens)) for _ in range(W)]
         for _ in range(H)]  # type: "List[List[int]]"
    solve(H, W, A, B)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")


def solve(H: int, W: int, A: "List[List[int]]", B: "List[List[int]]"):
    L = 160*80
    base = [[None]*W for _ in range(H)]
    for h in range(H):
        for w in range(W):
            base[h][w] = abs(A[h][w]-B[h][w])

    table = [[set() for _ in range(W)] for _ in range(H)]
    table[0][0].add(base[0][0])
    table[0][0].add(-base[0][0])
    for h in range(H):
        for w in range(W):
            if h > 0:
                for i in table[h-1][w]:
                    table[h][w].add(abs(i+base[h][w]))
                    table[h][w].add(abs(i-base[h][w]))
            if w > 0:
                for i in table[h][w-1]:
                    table[h][w].add(abs(i+base[h][w]))
                    table[h][w].add(abs(i-base[h][w]))
    print(min(table[H-1][W-1]))

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    A = [[int(next(tokens)) for _ in range(W)]
         for _ in range(H)]  # type: "List[List[int]]"
    B = [[int(next(tokens)) for _ in range(W)]
         for _ in range(H)]  # type: "List[List[int]]"
    solve(H, W, A, B)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")


def solve(H: int, W: int, A: "List[List[int]]", B: "List[List[int]]"):
    L = 160*80*2
    base = [[None]*W for _ in range(H)]
    for h in range(H):
        for w in range(W):
            base[h][w] = abs(A[h][w]-B[h][w])

    table = [[[False]*L for _ in range(W)] for _ in range(H)]
    table[0][0][base[0][0]] = True
    for h in range(H):
        for w in range(W):
            for i in range(L):
                a = abs(i-base[h][w])
                b = abs(i+base[h][w])
                if h > 0 and table[h-1][w][i] == True:
                    table[h][w][a] = True
                    table[h][w][b] = True
                if w > 0 and table[h][w-1][i] == True:
                    table[h][w][a] = True
                    table[h][w][b] = True
    for i in range(L):
        if table[H-1][W-1][i] == True:
            print(i)
            return

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    A = [[int(next(tokens)) for _ in range(W)]
         for _ in range(H)]  # type: "List[List[int]]"
    B = [[int(next(tokens)) for _ in range(W)]
         for _ in range(H)]  # type: "List[List[int]]"
    solve(H, W, A, B)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# E - Balanced Path
H, W = map(int, input().split())
a = [[0] * 100 for _ in range(100)]
for i in range(H):
    tmp = list(map(int, input().split()))
    for j in range(W):
        a[i][j] = tmp[j]
        
for i in range(H):
    tmp = list(map(int, input().split()))
    for j in range(W):
        a[i][j] = abs(tmp[j] - a[i][j])
        
center = 80 * 160
dp = [[[0] * (2 * center + 1) for _ in range(W)] for _ in range(H)]
dp[0][0][center + a[0][0]] = dp[0][0][center - a[0][0]] = 1
for i in range(H):
    for j in range(W):
        for k in range(2 * center + 1):
            # 上から下への遷移
            if i > 0 and dp[i - 1][j][k] == 1:
                dp[i][j][k + a[i][j]] = 1
                dp[i][j][k - a[i][j]] = 1
            # 左から右への遷移
            if j > 0 and dp[i][j - 1][k] == 1:
                dp[i][j][k + a[i][j]] = 1
                dp[i][j][k - a[i][j]] = 1

ans = center
for k in range(2 * center + 1):
    if dp[H - 1][W - 1][k] == 1:
        ans = min(ans, abs(k - center))
        
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)]
Diff = [[False] * (W + 1) for _ in range(H + 1)]
M = 0
for i in range(H):
    for j in range(W):
        m = abs(A[i][j] - B[i][j])
        Diff[i][j] = m
        M += m

dp = [[[0] * (M + 1) for _ in range(W + 1)] for _ in range(H + 1)]
dp[0][0][Diff[0][0]] = 1

for i in range(0, H):
    for j in range(0, W):
        for k in range(M + 1):
            if dp[i][j][k]:
                dp[i + 1][j][k + Diff[i + 1][j]] |= True
                dp[i + 1][j][abs(k - Diff[i + 1][j])] |= True
                dp[i][j + 1][k + Diff[i][j + 1]] |= True
                dp[i][j + 1][abs(k - Diff[i][j + 1])] |= True

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

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    h,w=map(int,input().split())
    a=[list(map(int,input().split())) for _ in [0]*h]
    b=[list(map(int,input().split())) for _ in [0]*h]
    c=[[abs(a[i][j]-b[i][j]) for j in range(w)] for i in range(h)]
    t=7160
    dp1=[[False]*(t+1) for _ in [0]*w]
    dp1[0][c[0][0]]=True
    for j in range(1,w):
        v=c[0][j]
        for k in range(t+1):
            if dp1[j-1][k]==True:
                if v+k<=t:
                    dp1[j][v+k]=True
                if abs(v-k)<=0:
                    dp1[j][abs(v-k)]=True
    for i in range(1,h):
        dp2=[[False]*(t+1) for _ in [0]*w]
        for j in range(w):
            v=c[i][j]
            for k in range(t+1):
                if dp1[j][k]==True:
                    if v+k<=t:
                        dp2[j][v+k]=True
                    if abs(v-k)<=t:
                        dp2[j][abs(v-k)]=True
        for j in range(1,w):
            v=c[i][j]
            for k in range(t+1):
                if dp2[j-1][k]==True:
                    if v+k<=t:
                        dp2[j][v+k]=True
                    if abs(v-k)<=t:
                        dp2[j][abs(v-k)]=True  
        dp1=dp2
    for i,j in enumerate(dp1[w-1]):
        if j==True:
            print(i)
            break
main()

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import numpy as np
    from sys import stdin
    f_i = stdin
    
    H, W = map(int, f_i.readline().split())
    A = tuple(tuple(map(int, f_i.readline().split())) for i in range(H))
    B = tuple(tuple(map(int, f_i.readline().split())) for i in range(H))
    
    dp1 = [dict() for i in range(W)]
    dp1[0][0] = True
    for A_i, B_i in zip(A, B):
        dp2 = [dict() for i in range(W)]
        
        diff = A_i[0] - B_i[0]
        for pre_bias in dp1[0]:
            dp2[0][abs(pre_bias + diff)] = True
            dp2[0][abs(pre_bias - diff)] = True
        
        for j, t in enumerate(zip(A_i[1:], B_i[1:]), start=1):
            A_ij, B_ij = t
            diff = A_ij - B_ij
            for pre_bias in dp1[j]:
                dp2[j][abs(pre_bias + diff)] = True
                dp2[j][abs(pre_bias - diff)] = True
            for pre_bias in dp2[j-1]:
                dp2[j][abs(pre_bias + diff)] = True
                dp2[j][abs(pre_bias - diff)] = True
                
        dp1 = dp2
    
    print(min(dp2[-1]))
 
solve()

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import numpy as np
    from sys import stdin
    f_i = stdin
    
    H, W = map(int, f_i.readline().split())
    A = tuple(tuple(map(int, f_i.readline().split())) for i in range(H))
    B = tuple(tuple(map(int, f_i.readline().split())) for i in range(H))
    
    max_bias = 80 * (W - 1) * (H - 1)
    dp1 = np.full((W, max_bias), False)
    dp1[0][0] = True
    for A_i, B_i in zip(A, B):
        dp2 = np.full((W, max_bias), False)
        diff = A_i[0] - B_i[0]
        for pre_bias in np.where(dp1[0] == True)[0]:
            dp2[0][abs(pre_bias + diff)] = True
            dp2[0][abs(pre_bias - diff)] = True
            
        for j, t in enumerate(zip(A_i[1:], B_i[1:]), start=1):
            A_ij, B_ij = t
            diff = A_ij - B_ij
            for pre_bias in np.where(dp1[j] == True)[0]:
                dp2[j][abs(pre_bias + diff)] = True
                dp2[j][abs(pre_bias - diff)] = True
            for pre_bias in np.where(dp2[j-1] == True)[0]:
                dp2[j][abs(pre_bias + diff)] = True
                dp2[j][abs(pre_bias - diff)] = True
        dp1 = dp2
    
    print(np.where(dp2[-1] == True)[0][0])
 
solve()