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:
# -*- coding: utf-8 -*-

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

def build_grid(H, W, intv, _type, space=True, padding=False):
    # 入力がスペース区切りかどうか
    if space:
        _input = lambda: input().split()
    else:
        _input = lambda: input()
    _list = lambda: list(map(_type, _input()))
    # 余白の有無
    if padding:
        offset = 1
    else:
        offset = 0
    grid = list2d(H+offset*2, W+offset*2, intv)
    for i in range(offset, H+offset):
        row = _list()
        for j in range(offset, W+offset):
            grid[i][j] = row[j-offset]
    return grid

H, W = MAP()
MAXV = 80 ** 2

grid1 =build_grid(H, W, 0, int)
grid2 =build_grid(H, W, 0, int)
grid = list2d(H+1, W+1, 0)
for i in range(H):
    for j in range(W):
        grid[i+1][j+1] = abs(grid1[i][j]-grid2[i][j])

dp = list3d(H+1, W+1, MAXV+1, 0)
dp[1][1][grid[1][1]] = 1
for i in range(1, H+1):
    for j in range(1, W+1):
        v = grid[i][j]
        for k in range(MAXV+1):
            dp[i][j][abs(k-v)] |= dp[i-1][j][k]
            if k+v <= MAXV:
                dp[i][j][k+v] |= dp[i-1][j][k]
            dp[i][j][abs(k-v)] |= dp[i][j-1][k]
            if k+v <= MAXV:
                dp[i][j][k+v] |= dp[i][j-1][k]
ans = INF
for k in range(MAXV+1):
    if dp[H][W][k]:
        ans = min(ans, k)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
h,w=map(int,input().split())
a=[]
for i in range(h):
    a.append(list(map(int,input().split())))
b=[]
for i in range(h):
    b.append(list(map(int,input().split())))
dp=[[set([]) for i in range(w)] for j 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):
        if i==j==0:
            continue
        if i==0:
            for k in dp[i][j-1]:
                dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        elif j==0:
            for k in dp[i-1][j]:
                dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        else:
            for k in (dp[i][j-1]|dp[i-1][j]):
                if k<=80*80*80:
                    dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                    dp[i][j].add(abs(k+b[i][j]-a[i][j]))             
#dp[h-1][w-1]
ans=10**10
for i in dp[h-1][w-1]:
    ans=min(ans,abs(i))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import defaultdict

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

mod = 10**9 + 7

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

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


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


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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
h, w = map(int, input().split())
graph = []
for i in range(h):
    a = list(map(int, sys.stdin.readline().split()))
    graph.append(a)
for i in range(h):
    b = list(map(int, sys.stdin.readline().split()))
    for j in range(w):
        graph[i][j] = abs(graph[i][j] - b[j])
result = [[set()]*w for _ in range(h)]
result[0][0].add(graph[0][0])
for i in range(1, h+w-1):
    for j in range(max(0, i-(w-1)), min(i+1, h)):
        ps = set()
        if j > 0:
            for k in result[j-1][i-j]:
                em = abs(k - graph[j][i-j])
                ps.add(em)
                eu = k + graph[j][i-j]
                if k <= 80 * (h + w) // 2 +1:
                    ps.add(eu)
        if i-j > 0:
            for k in result[j][i-j-1]:
                em = abs(k - graph[j][i-j])
                ps.add(em)
                eu = k + graph[j][i-j]
                if k <= 80 * (h + w) // 2 +1:
                    ps.add(eu)
        result[j][i-j] = ps
print(min(result[h-1][w-1]))

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
grid_a = []
grid_b = []
for i in range(H):
  grid_a.append(list(map(int,input().split())))
for i in range(H):
  grid_b.append(list(map(int,input().split())))
  
def get_diff(x,y): 
  return grid_a[y][x] - grid_b[y][x]

diff = grid_a[0][0] - grid_b[0][0]
q = [(0,0,diff)] 
min_diff = 80
while q:
  cx,cy,cd = q.pop()
  if cx!=W-1:
    q.append((cx+1,cy,cd+get_diff(cx+1,cy)))
    q.append((cx+1,cy,cd-get_diff(cx+1,cy)))
  if cy!=H-1:
    q.append((cx,cy+1,cd+get_diff(cx,cy+1)))
    q.append((cx,cy+1,cd-get_diff(cx,cy+1)))
  if cx==W-1 and cy==H-1:
    min_diff = min(min_diff,abs(cd))
print(min_diff)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

def solve():
    input = sys.stdin.readline
    H, W = map(int, input().split())
    grid = dict() #絶対値
    dist = dict()
    for h in range(H):
        grid[h] = dict()
        dist[h] = dict()
        for w in range(W):
            grid[h][w] = 0
            dist[h][w] = set()

    for h in range(H):
        A = [int(a) for a in input().split()]
        for w in range(W):
            grid[h][w] = A[w]
    for h in range(H):
        B = [int(b) for b in input().split()]
        for w in range(W):
            grid[h][w] = abs(grid[h][w] - B[w])
    #print(grid)

    dist[0][0] |= {grid[0][0]}
    for h in range(H):
        for w in range(W):
            for item in dist[h][w]:
                if h < H - 1:
                    n = grid[h+1][w]
                    dist[h+1][w] |= {abs(item + n)}
                    dist[h+1][w] |= {abs(item - n)}
                if w < W - 1:
                    n = grid[h][w+1]
                    dist[h][w+1] |= {abs(item + n)}
                    dist[h][w+1] |= {abs(item - n)}

    #print(dist)
    ans = 1000000
    for item in dist[H-1][W-1]:
        ans = min(ans, item)
    print(ans)

    return 0

if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
h,w=map(int,input().split())
a=[list(map(int,input().split()))for i in range(h)]
b=[list(map(int,input().split()))for i in range(h)]
c=[[abs(a[i][j]-b[i][j])for j in range(w)]for i in range(h)]
d=[[set()for i in range(w+1)]for j in range(h+1)]
d[1][1]=set([c[0][0]])
for x in range(1,h+1):
    for y in range(1,w+1):
        if not (x==1 and y==1):
            a=d[x-1][y]|d[x][y-1]
            for i in a:
                d[x][y].add(abs(i-c[x-1][y-1]))
                d[x][y].add(i+c[x-1][y-1])
print(min(d[h][w]))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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,A[0][0],B[0][0]])
q.append([0,0,B[0][0],A[0][0]])
ans = float('inf')
while len(q) > 0:
  prvi, prvj, prv_val1, prv_val2 = 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, abs((prv_val1+A[j][i])-(prv_val2+B[j][i])))
      ans = min(ans, abs((prv_val1+B[j][i])-(prv_val2+A[j][i])))
    else:
      q.append([i, j, prv_val1+A[j][i], prv_val2+B[j][i]])
      q.append([i, j, prv_val1+B[j][i], prv_val2+A[j][i]])

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)]
g = [[0]*w for _ in range(h)]
for i in range(h):
  for j in range(w):
    g[i][j] = abs(a[i][j] - b[i][j])
a = b = 0
dp = [[[False]*6400 for _ in range(w+1)] for _ in range(h+1)]
dp[0][1][0] = True
dp[1][0][0] = True
for i in range(1,h+1):
  for j in range(1,w+1):
    for x in range(6400):
      if dp[i-1][j][x] or dp[i][j-1][x]:
        dp[i][j][abs(x-g[i-1][j-1])] |= True
        if x + g[i-1][j-1] < 6400:
            dp[i][j][x+g[i-1][j-1]] |= True
for x in range(6400):
  if dp[h][w][x]:
    print(x)
    break

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
h,w=map(int,input().split())
a=[]
for i in range(h):
    a.append(list(map(int,input().split())))
b=[]
for i in range(h):
    b.append(list(map(int,input().split())))
dp=[[set([]) for i in range(w)] for j 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):
        if i==j==0:
            continue
        if i==0:
            for k in dp[i][j-1]:
                #if k+a[i][j]-b[i][j]>=0:
                dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                #if -k+a[i][j]-b[i][j]>=0:
                  #  dp[i][j].add(-k+a[i][j]-b[i][j])
                #if k+b
                dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        elif j==0:
            for k in dp[i-1][j]:
                dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                dp[i][j].add(abs(k+b[i][j]-a[i][j]))
        else:
            for k in (dp[i][j-1]|dp[i-1][j]):
                dp[i][j].add(abs(k+a[i][j]-b[i][j]))
                dp[i][j].add(abs(k+b[i][j]-a[i][j]))             
#dp[h-1][w-1]
ans=10**10
for i in dp[h-1][w-1]:
    ans=min(ans,abs(i))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
A = []
for _ in range(H):
    A.append(list(map(int, input().split())))
B = []
C = []
for y in range(H):
    B.append(list(map(int, input().split())))
    C.append(list(abs(a-b) for (a, b) in zip(A[y], B[y])))
VMAX = 159*80+1
dp = [[[0] * VMAX for _ in range(W)] for _ in range(H)]
dp[0][0][C[0][0]] = 1
for y in range(H):
    for x in range(W):
        if y==0 and x==0:
            continue
        for v in range(VMAX):
            if y-1 >= 0 and dp[y-1][x][v]:
                dp[y][x][abs(v+C[y][x])] = 1
                dp[y][x][abs(v-C[y][x])] = 1
            if x-1 >= 0 and dp[y][x-1][v]:
                dp[y][x][abs(v+C[y][x])] = 1
                dp[y][x][abs(v-C[y][x])] = 1
ans = -1
for v in range(VMAX):
    if dp[-1][-1][v]:
        ans = v
        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 = [[abs(a[i][j] - b[i][j]) for j in range(w)] for i in range(h)]


def div(s):
    s.sort(reversed=True)
    a = []
    b = []
    total_a = 0
    total_b = 0
    for v in a:
        if total_a < total_b:
            total_a += v
            a.append(v)
        else:
            total_b += v
            b.append(v)
    return (a, b)


sets = [[set() for j in range(w)] for i in range(h)]
sets[0][0].add(c[0][0])
for i in range(1, h):
    for e in sets[i-1][0]:
        sets[i][0].add(e + c[i][0])
        sets[i][0].add(abs(e - c[i][0]))
for i in range(1, w):
    new_set = set()
    for e in sets[0][i-1]:
        sets[0][i].add(e+c[0][i])
        sets[0][i].add(abs(e-c[0][i]))

for i in range(1, h):
    for j in range(1, w):
        for e in sets[i-1][j]:
            sets[i][j].add(e+c[i][j])
            sets[i][j].add(abs(e-c[i][j]))
        for e in sets[i][j-1]:
            sets[i][j].add(e+c[i][j])
            sets[i][j].add(abs(e-c[i][j]))
print(min(sets[h-1][w-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)]
# abs(A - B)
S = [[abs(a - b) for a, b in zip(A[n], B[n])] for n in range(H)]

setS = [[set() for _ in range(W)] for _ in range(H)]

setS[0][0].add(S[0][0])

for i in range(H):
    for j in range(W):
        if i == 0 and j == 0:
           continue
        if i > 0:
            for a in list(setS[i-1][j]):
                setS[i][j].add(abs(a + S[i][j]))
                setS[i][j].add(abs(a - S[i][j]))
        if j > 0:
            for a in list(setS[i][j-1]):
                setS[i][j].add(abs(a + S[i][j]))
                setS[i][j].add(abs(a - S[i][j]))

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

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline

ri = lambda: int(input())
rs = lambda: input().rstrip()
ril = lambda: list(map(int, input().split()))
rsl = lambda: input().rstrip().split()
ris = lambda n: [ri() for _ in range(n)]
rss = lambda n: [rs() for _ in range(n)]
rils = lambda n: [ril() for _ in range(n)]
rsls = lambda n: [rsl() for _ in range(n)]

h, w = ril()
ls0 = rils(h)
ls1 = rils(h)

nums = [[set() for _ in range(w)] for _ in range(h)]
nums[0][0].add(abs(ls0[0][0] - ls1[0][0]))
for i in range(h):
    for j in range(w):
        x = abs(ls0[i][j] - ls1[i][j])
        if i > 0:
            for y in nums[i - 1][j]:
                nums[i][j].add(abs(x + y))
                nums[i][j].add(abs(x - y))
        if j > 0:
            for y in nums[i][j - 1]:
                nums[i][j].add(abs(x + y))
                nums[i][j].add(abs(x - y))
print(min(nums[h - 1][w - 1]))

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
grid_a = [[0 for i in range(W)] for j in range(H)]
grid_b = [[0 for i in range(W)] for j in range(H)]
for i in range(H):
  grid_a[i] = list(map(int,input().split()))
for i in range(H):
  grid_b[i] = list(map(int,input().split()))
  
def get_diff(x,y): 
  return grid_a[y][x] - grid_b[y][x]

diff = grid_a[0][0] - grid_b[0][0]
q = [(0,0,diff)] 
min_diff = 80
while q:
  cx,cy,cd = q.pop()
  if cx!=W-1:
    q.append((cx+1,cy,cd+get_diff(cx+1,cy)))
    q.append((cx+1,cy,cd-get_diff(cx+1,cy)))
  if cy!=H-1:
    q.append((cx,cy+1,cd+get_diff(cx,cy+1)))
    q.append((cx,cy+1,cd-get_diff(cx,cy+1)))
  if cx==W-1 and cy==H-1:
    min_diff = min(min_diff,abs(cd))
print(min_diff)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

input = sys.stdin.readline

ri = lambda: int(input())
rs = lambda: input().rstrip()
ril = lambda: list(map(int, input().split()))
rsl = lambda: input().rstrip().split()
ris = lambda n: [ri() for _ in range(n)]
rss = lambda n: [rs() for _ in range(n)]
rils = lambda n: [ril() for _ in range(n)]
rsls = lambda n: [rsl() for _ in range(n)]

h, w = ril()
ls0 = np.array(rils(h))
ls1 = np.array(rils(h))
ls = np.abs(ls0 - ls1)

nums = [[set() for _ in range(w)] for _ in range(h)]
nums[0][0].add(ls[0, 0])
for i in range(h):
    for j in range(w):
        x = ls[i][j]
        if i > 0:
            for y in nums[i - 1][j]:
                nums[i][j].add(abs(x + y))
                nums[i][j].add(abs(x - y))
        if j > 0:
            for y in nums[i][j - 1]:
                nums[i][j].add(abs(x + y))
                nums[i][j].add(abs(x - y))
print(min(nums[h - 1][w - 1]))

Submission status: Time Limit Exceeded

Solution code:
h,w=[int(j) for j in input().split()]
a=[]
b=[]
for i in range(h):
    a.append([int(j) for j in input().split()])
for i in range(h):
    b.append([int(j) for j in input().split()])
l=[[] for i in range(h)]
for i in range(h):
    for j in range(w):
        l[i].append(abs(a[i][j]-b[i][j]))
ans=[[set() for j in range(w)] for i in range(h)]
ans[0][0].add(l[0][0])
for i in range(h):
    for j in range(w):
        for k in ans[i][j]:
            if i+1<h:
                ans[i+1][j].add(k+l[i+1][j])
                ans[i+1][j].add(k-l[i+1][j])
            if j+1<w:
                ans[i][j+1].add(k+l[i][j+1])
                ans[i][j+1].add(k-l[i][j+1])
a=10**18
for i in ans[h-1][w-1]:
    a=min(abs(i),a)
print(a)

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)]
diff = [[0]*(w+1) for i in range(h+1)]

for i in range(h):
    for j in range(w):
        diff[i][j] = abs(a[i][j] - b[i][j])

n = 80 * 80 + 1
dp = [[False]*n for i in range(h*w)]
dp[0][diff[0][0]] = True

for i in range(h):
    for j in range(w):
        for cnt in range(n):
            if dp[i*w + j][cnt]:
                tmp1 = diff[i+1][j]
                tmp2 = diff[i][j+1]

                if i+1 < h:
                    dp[(i+1)*w + j][abs(cnt - tmp1)] = True
                    if cnt + tmp1 < n:
                        dp[(i+1)*w + j][cnt + tmp1] = True

                if j+1 < w:
                    dp[i*w + j+1][abs(cnt - tmp2)] = True 
                    if cnt + tmp2 < n:
                        dp[i*w + j+1][cnt + tmp2] = True

for i, boo in enumerate(dp[w*h - 1][0:81]):
    if boo:
        print(i)
        exit()
print(a[10*9])

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.buffer.readline
from heapq import *

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

Submission status: Time Limit Exceeded

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

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

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


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

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

DP=[[[] for i in range(W+1)] for i in range(H+1)]

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

MID=(H+W-2)//2

def next(i,j,t):
    if t<=MID:
        return [i+j,abs(i-j)]
    RET=[]
    lim=80*(MID-abs(t-MID)+2)
    if i+j<=lim:
        RET.append(i+j)

    if abs(i-j)<=lim:
        RET.append(abs(i-j))

    return RET

for i in range(H):
    for j in range(W):
        for k in set(DP[i][j]):
            DP[i+1][j].extend(next(k,SA[i+1][j],i+j))
            DP[i][j+1].extend(next(k,SA[i][j+1],i+j))
                
print(min(DP[H-1][W-1]))

Submission status: Time Limit Exceeded

Solution code:

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

A = []

for i in range(H):

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

B = []

for i in range(H):

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

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

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

C = [[[False] * 6401  for i in range(W)] for j in range(H)]


for i in range(H):

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

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

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

#print (C)

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

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

        for k in range(6401):

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

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

#print (C)
ans = float("inf")   
for i in range(6401):

    if C[-1][-1][i]:
        ans = min(ans,i)
    
print (ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(H)]
B = [list(map(int, input().split())) for _ in range(H)]
C = [[0]*W for _ in range(H)]
for i in range(H):
    for j in range(W):
        C[i][j] = A[i][j]-B[i][j]
M = 80*(H+W)
dp = [set() for j in range(H)]
c = C[0][0]
dp[0].add(c)
dp[0].add(-c)
for i in range(1, H):
    c = C[i][0]
    for j in dp[i-1]:
        dp[i].add(j+c)
        dp[i].add(j-c)
for i in range(1, W):
    dp1 = [set() for j in range(H)]
    c = C[0][i]
    for k in dp[0]:
        dp1[0].add(k+c)
        dp1[0].add(k-c)
    for j in range(1, H):
        c = C[j][i]
        for k in dp[j]:
            dp1[j].add(k+c)
            dp1[j].add(k-c)
        for k in dp1[j-1]:
            dp1[j].add(k+c)
            dp1[j].add(k-c)
    dp = dp1

ans = min(abs(i) for i in dp[-1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# ABC147e


def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**6)

    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[i][j]=マスi,jでありえる赤への偏りのパターン（リスト）
    dp = [[set() for _ in range(w)] for j in range(h)]
    dp[0][0] = set([a[0][0]-b[0][0], b[0][0]-a[0][0]])

    for i in range(h):
        for j in range(w):
            for k in dp[i][j]:
                if j+1 < w:
                    nk = k + a[i][j+1] - b[i][j+1]
                    dp[i][j + 1].add(nk)
                    nk = k + b[i][j+1] - a[i][j+1]
                    dp[i][j + 1].add(nk)
                if i + 1 < h:
                    nk = k + b[i+1][j] - a[i+1][j]
                    dp[i + 1][j].add(nk)
                    nk = k + a[i+1][j] - b[i+1][j]
                    dp[i + 1][j].add(nk)
    ans = 10 ** 9
    for i in dp[h - 1][w - 1]:
        ans = min(ans, abs(i))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
h,w=map(int,input().split())
a=[list(map(int,input().split()))for i in range(h)]
b=[list(map(int,input().split()))for i in range(h)]
c=[[abs(a[i][j]-b[i][j])for j in range(w)]for i in range(h)]
d=[[set()for i in range(w+1)]for j in range(h+1)]
d[1][1]=set([-c[0][0],c[0][0]])
for x in range(1,h+1):
    for y in range(1,w+1):
        if not (x==1 and y==1):
            a=d[x-1][y]|d[x][y-1]
            for i in a:
                d[x][y].add(i-c[x-1][y-1])
                d[x][y].add(i+c[x-1][y-1])
print(abs(min(d[h][w],key=abs)))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
h,w=map(int,input().split())
a=[]
for i in range(h):
    a.append(list(map(int,input().split())))
b=[]
for i in range(h):
    b.append(list(map(int,input().split())))
dp=[[set([]) for i in range(w)] for j 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):
        if i==j==0:
            continue
        if i==0:
            for k in dp[i][j-1]:
                dp[i][j].add(k+a[i][j]-b[i][j])
                dp[i][j].add(k+b[i][j]-a[i][j])
        elif j==0:
            for k in dp[i-1][j]:
                dp[i][j].add(k+a[i][j]-b[i][j])
                dp[i][j].add(k+b[i][j]-a[i][j])
        else:
            for k in (dp[i][j-1]|dp[i-1][j]):
                dp[i][j].add(k+a[i][j]-b[i][j])
                dp[i][j].add(k+b[i][j]-a[i][j])             
#dp[h-1][w-1]
ans=10**10
for i in dp[h-1][w-1]:
    ans=min(ans,abs(i))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
	return sys.stdin.readline()[:-1]

H, W = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(H)]
b = [list(map(int, input().split())) for _ in range(H)]
c = [[0 for _ in range(W)] for _ in range(H)]
for i in range(H*W):
	h, w = i//W, i%W
	c[h][w] = abs(a[h][w] - b[h][w])

#print(*c, sep="\n")
s = [[set() for _ in range(W)] for _ in range(H)]
s[0][0].add(c[0][0])
for i in range(H*W):
	h, w = i//W, i%W
	c[h][w] = abs(a[h][w] - b[h][w])
	for x in s[h][w]:
		if h < H-1:
			s[h+1][w].add(x + c[h+1][w])
			s[h+1][w].add(abs(x - c[h+1][w]))
		if w < W-1:
			s[h][w+1].add(x + c[h][w+1])
			s[h][w+1].add(abs(x - c[h][w+1]))

ans = 100000
for x in s[H-1][W-1]:
	ans = min(ans, abs(x))
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)]
diff = [[0]*(w+1) for i in range(h+1)]

for i in range(h):
    for j in range(w):
        diff[i][j] = abs(a[i][j] - b[i][j])

n = 80 * 80 + 1
dp = [[False]*n for i in range(h*w)]
dp[0][diff[0][0]] = True

for i in range(h):
    for j in range(w):
        for cnt in range(n):
            if dp[i*w + j][cnt]:

                if i+1 < h and cnt + diff[i+1][j] < 80 * 80 + 1:
                    dp[i*w+w + j][cnt + diff[i+1][j]] = True
                if i+1 < h:
                    dp[i*w+w + j][abs(cnt - diff[i+1][j])] = True

                if j+1 < w and cnt + diff[i][j+1] < 80 * 80 + 1:
                    dp[i*w + j+1][cnt + diff[i][j+1]] = True
                if j+1 < w:
                    dp[i*w + j+1][abs(cnt - diff[i][j+1])] = True 

for i, boo in enumerate(dp[w*h - 1][0:81]):
    if boo:
        print(i)
        exit()
print(a[10*9])

Submission status: Time Limit Exceeded

Solution code:
h,w=map(int,input().split())
a=[]
for i in range(h):
    a.append(list(map(int,input().split())))
b=[]
for i in range(h):
    b.append(list(map(int,input().split())))
dp=[[set([]) for i in range(w)] for j 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):
        if i==j==0:
            continue
        if i==0:
            for k in dp[i][j-1]:
                dp[i][j].add(k+a[i][j]-b[i][j])
                dp[i][j].add(k+b[i][j]-a[i][j])
        elif j==0:
            for k in dp[i-1][j]:
                dp[i][j].add(k+a[i][j]-b[i][j])
                dp[i][j].add(k+b[i][j]-a[i][j])
        else:
            for k in (dp[i][j-1]|dp[i-1][j]):
                dp[i][j].add(k+a[i][j]-b[i][j])
                dp[i][j].add(k+b[i][j]-a[i][j])             
#dp[h-1][w-1]
ans=10**10
for i in dp[h-1][w-1]:
    ans=min(ans,abs(i))
print(ans)