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: Runtime Error

Solution code:
import sys
import math
import bisect
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop


def LI(): return [int(x) for x in sys.stdin.readline().split()]


def I(): return int(sys.stdin.readline())


def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res


def IR(n):
    return [I() for i in range(n)]


# A
def A():
    a, b, c = LI()
    if a + b + c >= 22:
        print("bust")
    else:
        print("win")
    return


# B
def B():
    s = S()
    ans = 0
    for i in range(len(s) // 2):
        if s[i] != s[-i - 1]:
            ans += 1
    print(ans)
    return


# C
def C():
    n = I()
    res = [[0] * n for i in range(n)]
    ans = 0
    for i in range(n):
        a = I()
        for j in range(a):
            x, y = LI()
            if y == 0:
                res[i][x - 1] = 1
    while (1):
        max_num = 0
        max_ind = -1
        for i in range(n):
            num = 0
            for j in range(n):
                if i == j:
                    num += sum(res[i])
                else:
                    if res[j][i] == 1:
                        num += 1
            if num > max_num:
                max_num = num
                max_ind = i
        if max_ind == -1:
            print(n - ans)
            return
        else:
            ans += 1
            res[max_ind] = [0] * n
            for i in range(n):
                res[i][max_ind] = 0
    return


# D
def D():
    return


# E
def E():
    h, w = LI()
    a = [LI() for i in range(h)]
    b = [LI() for i in range(h)]
    dp = [[[0] * 100 for i in range(w)] for i in range(h)]
    dp[0][0][abs(a[0][0] - b[0][0])] = 1
    for i in range(1, h):
        for num in range(100):
            if dp[i - 1][0][num] == 1:
                dp[i][0][abs(num + abs(a[i][0] - b[i][0]))] = 1
                dp[i][0][abs(num - abs(a[i][0] - b[i][0]))] = 1
    for i in range(1, w):
        for num in range(100):
            if dp[0][i - 1][num] == 1:
                dp[0][i][abs(num + abs(a[0][i] - b[0][i]))] = 1
                dp[0][i][abs(num - abs(a[0][i] - b[0][i]))] = 1
    for i in range(1, h):
        for j in range(1, w):
            for num in range(100):
                if dp[i - 1][j][num] == 1:
                    dp[i][j][abs(num + abs(a[i][j] - b[i][j]))] = 1
                    dp[i][j][abs(num - abs(a[i][j] - b[i][j]))] = 1
                if dp[i][j - 1][num] == 1:
                    dp[i][j][abs(num + abs(a[i][j] - b[i][j]))] = 1
                    dp[i][j][abs(num - abs(a[i][j] - b[i][j]))] = 1
    for i in range(100):
        if dp[h-1][w-1][i] == 1:
            print(i)
            break
    return


# F
def F():
    return


# Unittest
def resolve():
    E()
    return


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

Submission status: Runtime Error

Solution code:
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(b-a) for a,b in zip(a_row,b_row)] for a_row,b_row in zip(A,B)]

dm = [[0]*W for _ in [0]*H]
dm[-1][-1] = 80
for i in range(H-1,-1,-1):
    for j in range(W-1,-1,-1):
        c = C[i][j]
        if i-1>0:
            dm[i-1][j] = max(dm[i-1][j],dm[i][j] + c)
        if j-1>0:
            dm[i][j-1] = max(dm[i-1][j],dm[i][j] + c)

d = [[set() for _ in [0]*W] for _ in [0]*H]
d[0][0] = {C[0][0]}

for i in range(H):
    for j in range(W):
        for n in d[i][j]:
            if i+1<H:
                c = C[i+1][j]
                if n+c <= dm[i][j]:
                    d[i+1][j].add(n+c)
                if n-c <= dm[i][j]:
                    d[i+1][j].add(abs(n-c))
            if j+1<W:
                c = C[i][j+1]
                if n+c <= dm[i][j]:
                    d[i][j+1].add(n+c)
                if n-c <= dm[i][j]:
                    d[i][j+1].add(abs(n-c))
ans = min(abs(o) for o in d[-1][-1])
print(ans)

Submission status: Runtime Error

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)]
d=[[0 for i in range(w)] for j in range(h)]
for i in range(h):
    for j in range(w):
        d[i][j] = abs(a[i][j]-b[i][j])
dp=[[[] for j in range(w)] for k in range(h)]
dp[0][0].append(d[0][0])
for i in range(h):
    for j in range(w):
        for x in dp[i][j]:
            if i+1<h:
                dp[i+1][j].append(dis+d[i+1][j])
                dp[i+1][j].append(abs(dis-d[i+1][j]))
            if j+1<w:
                dp[i][j+1].append(dis+d[i][j+1])
                dp[i][j+1].append(abs(dis-d[i][j+1]))
m=10000000
for dis in dp[-1][-1]:
    m=min(m,dis)
print(m)

Submission status: Runtime Error

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)]
d=[[0 for i in range(w)] for j in range(h)]
for i in range(h):
    for j in range(w):
        d[i][j] = abs(a[i][j]-b[i][j])
dp=[[[]] for j in range(w)] for k in range(h)]
dp[0][0].append(d[0][0])
for i in range(h):
    for j in range(w):
        for x in dp[i][j]:
            if i+1<h:
                dp[i+1][j].append(dis+d[i+1][j])
                dp[i+1][j].append(abs(dis-d[i+1][j]))
            if j+1<w:
                dp[i][j+1].append(dis+d[i][j+1])
                dp[i][j+1].append(abs(dis-d[i][j+1]))
m=10000000
for dis in dp[-1][-1]:
    m=min(m,dis)
print(m)

Submission status: Runtime Error

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

def main():
    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)]
    L = 80*80*4
    mid = L//2
    dp = [[[False]*(L+1) for _ in range(W+1)] for _ in range(H+1)]
    for h in range(H+1):
        dp[h][0][mid] = True
    for w in range(H+1):
        dp[0][w][mid] = True
    
    for h in range(H):
        for w in range(W):
            for l in range(L+1):
                c = A[h][w] - B[h][w]
                if 0 <= l-c <= L:
                    dp[h+1][w+1][l] = dp[h][w+1][l-c] or dp[h+1][w][l-c]
                if 0 <= l+c <= L:
                    dp[h+1][w+1][l] = dp[h+1][w+1][l] or dp[h][w+1][l+c] or dp[h+1][w][l+c]
    ans = 10**9
    for l in range(L+1):
        if dp[H][W][l]:
            ans = min(abs(l-mid), ans)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

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)]
d=[[0 for i in range(w)] for j in range(h)]
for i in range(h):
    for j in range(w):
        d[i][j] = abs(a[i][j]-b[i][j])
dp=[[[False for i in range(80*160)] for j in range(w)] for k in range(h)]
dp[0][0][d[0][0]] = True
for i in range(h):
    for j in range(w):
        for dis in range(80*160):
            if dp[i,j,dis]:
                if i+1<h:
                    dp[i+1][j][dis+d[i+1][j]]=True
                    dp[i+1][j][abs(dis-d[i+1][j])]=True
                if j+1<w:
                    dp[i][j+1][dis+d[i][j+1]]=True
                    dp[i][j+1][abs(dis-d[i][j+1])]=True
for dis in range(80*160):
    if dp[-1][-1][dis]:
        print(dis)
        break

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split())
A = [[0 for i in range(W)] for i in range(H)]
B = [[0 for i in range(W)] for i in range(H)]
C = [[0 for i in range(W)] for i in range(H)]
for i in range(H):
    A[i] = list(map(int,input().split()))
for i in range(H):
    B[i] = list(map(int,input().split()))
for i in range(H):
    for j in range(W):
        C[i][j] = max(A[i][j] - B[i][j], - A[i][j] + B[i][j])
D = [[[0 for i in range(80)] for i in range(W)] for i in range(H)]
D[0][0][C[0][0]] = 1
for i in range(H):
    for j in range(W):
        c = C[i][j]
        for k in range(80):
            if k-c >= 0:
                D[i][j][k] = max(D[max(i-1,0)][j][k-c],D[i][max(j-1,0)][k-c])
            else:
                D[i][j][k] = max(D[max(i-1,0)][j][c-k],D[i][max(j-1,0)][c-k])
E = D[H-1][W-1]
ans = 80
for i in range(80):
    if E[i] == 1:
        ans = i
        break
print(ans)

Submission status: Runtime Error

Solution code:
from itertools import chain

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

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

dp = {(0,0) : {(A[0][0]-B[0][0])%160, (B[0][0]-A[0][0])%160}}


for t in range(1,H+W-1):
    ndp = dict()
    for x in range(max(0,t-H+1), min(t+1,W)):
        y = t-x
        d = A[y][x]-B[y][x]
        if x > 0 and y > 0:
            ns = set(k%160 for k in chain((v+d for v in dp[(x-1,y)]),
                            (v-d for v in dp[(x-1,y)]),
                            (v+d for v in dp[(x,y-1)]),
                            (v-d for v in dp[(x,y-1)]),))
        elif x > 0:
            ns = set(k%160 for k in chain((v+d for v in dp[(x-1,y)]),
                            (v-d for v in dp[(x-1,y)]),))
        elif y > 0:
            ns = set(k%160 for k in chain((v+d for v in dp[(x,y-1)]),
                            (v-d for v in dp[(x,y-1)]),))
        else:
            ns = set()

        ndp[(x,y)] = ns
    dp = ndp

print(min(dp[(W-1,H-1)], (160-v for v in dp[(W-1,H-1)] ))

Submission status: Runtime Error

Solution code:
#!/bin/bash
''':'
docker run --rm -it -v $(cd $(dirname $0) && pwd):/vo:ro pypy:3-2.4.0 /bin/bash -c "pypy3 /vo/$(basename $0) < /vo/g.inp"; exit $?
exit 0
'''
import sys
import math

def _i(): return int(sys.stdin.readline().strip())
def _ia(): return [ int(x) for x in sys.stdin.readline().strip().split() ]

h,w = _ia()
ab = []
for _ in range(h): ab.append(_ia())
for i in range(h):
    r = ab[i]
    for j,bj in enumerate(_ia()):
        r[j] = abs(r[j] - bj)
#        
def search(ab,i,j,now=0):
    if i==-1 or j==-1: return math.inf
    if i==0 and j==0:
        ret = ab[0][0]
        if now>0: return abs(now - ret)
        else: return abs(now + ret)
    #
    x = ab[i][j]
    t1 = search(ab,i-1,j,now+x)
    t2 = search(ab,i-1,j,now-x)
    t3 = search(ab,i,j-1,now+x)
    t4 = search(ab,i,j-1,now-x)
    return min(t1,t2,t3,t4)

h1 = h - 1
w1 = w - 1
print(search(ab,h1,w1))

Submission status: Runtime Error

Solution code:
import copy
h,w=map(int,input().split())
a=[list(map(int,input().split())) for i in range(h)]
b=[list(map(int,input().split())) for i in range(h)]
c=[[0]*w for i in range(h)]
for i in range(h):
  for j in range(w):
    c[i][j]=abs(a[i][j]-b[i][j])
dp=[[[] for i in range(w)] for j in range(h)]
dp[0][0].append(c[0][0])
for i in range(h):
  for j in range(w):
    f=0
    if i<h-1:
      l=[]
      for k in range(len(dp[i][j])):
        if -80<=dp[i][j][k]+c[i+1][j]<=80:
          l.append(dp[i][j][k]+c[i+1][j])
        if -80<=l[k]-c[i+1][j]<=80:
          l.append(dp[i][j][k]-c[i+1][j])
      l=list(set(l))
      dp[i+1][j]=l+dp[i+1][j]
      dp[i+1][j]=list(set(dp[i+1][j]))
    f=0
    if j<w-1:
      l=[]
      for k in range(len(dp[i][j])):
        if -80<=dp[i][j][k]+c[i][j+1]<=80:
          l.append(dp[i][j][k]+c[i][j+1])
        if -80<=dp[i][j][k]-c[i][j+1]<=80:
          l.append(dp[i][j][k]-c[i][j+1])
      l=list(set(l))
      dp[i][j+1]=l+dp[i][j+1]
      dp[i][j+1]=list(set(dp[i][j+1]))
for i in range(len(dp[h-1][w-1])):
  dp[h-1][w-1][i]=abs(dp[h-1][w-1][i])
print(min(dp[h-1][w-1]))

Submission status: Runtime Error

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]:
                if z <= 80 * 81:
                    nums[i][j].add(abs(x + y))
                nums[i][j].add(abs(x - y))
        if j > 0:
            for y in nums[i][j - 1]:
                if z <= 80 * 81:
                    nums[i][j].add(abs(x + y))
                nums[i][j].add(abs(x - y))
print(min(nums[h - 1][w - 1]))

Submission status: Runtime Error

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,w+1):
    for y in range(1,h+1):
        if not (i==1 and j==1):
            a=d[x-1][y]|d[x][y-1]
            for i in a:
                d[x][y].add(i-c[x-1][y-1])
                if i+c[x-1][y-1]<=80*(h+w-x-y+1)
                    d[x][y].add(i+c[x-1][y-1])
print(abs(min(d[h][w],key=abs)))

Submission status: Runtime Error

Solution code:
h, w = map(int, input().split())
a = [input().split() for _ in range(h)]
b = [input().split() for _ in range(h)]
c = [[abs(a[i][j] - b[i][j]) for j in range(w)] for i in range(h)]

dp = [[set() for j in range(w)] for i in range(h)]
dp[i][j].add(c[i][j])
for j in range(1, range(w)):
  for num in dp[0][j-1]:
    dp[0][j].add(abs(c[0][j] - num))
    dp[0][j].add(c[0][j] + num)
for i in range(1, range(h)):
  for num in dp[i-1][0]:
    dp[i][0].add(abs(c[i][0] - num))
    dp[i][0].add(c[i][0] + num)
for i in range(1, range(h)):
  for j in range(1, range(w)):
    for num in dp[i][j-1]:
      dp[i][j].add(abs(c[i][j] - num))
      dp[i][j].add(c[i][j] + num)
    for num in dp[i-1][j]:
      dp[i][j].add(abs(c[i][j] - num))
      dp[i][j].add(c[i][j] + num)
print(min(list(dp[-1][-1])))

Submission status: Runtime Error

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

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

max_f = [[0] * (w+1) for _ in range(h+1)]
min_f = [[0] * (w+1 )for _ in range(h+1)]
# dp[height][width][bias]
dp = [[[0] * MAX_VAL for _ in range(w+1)] for _ in range(h+1)] 
max_f[0][0] = abs(a[0][0] - b[0][0])
min_f[0][0] = -abs(a[0][0] - b[0][0])

dp[0][0][OFFSET + a[0][0] - b[0][0]] = 1
dp[0][0][OFFSET + b[0][0] - a[0][0]] = 1
for i in range(h):
    for j in range(w):
        diffr = a[i][j+1] - b[i][j+1]
        diffd = a[i+1][j] - b[i+1][j]
        max_f[i][j+1] = max(max_f[i][j+1], max_f[i][j] + diffr)
        min_f[i][j+1] = min(min_f[i][j+1], min_f[i][j] - diffr)
        max_f[i+1][j] = max(max_f[i+1][j], max_f[i][j] + diffd)
        min_f[i+1][j] = min(min_f[i+1][j], min_f[i][j] - diffd)

        max_f[i][j+1] = min(OFFSET-10, max_f[i][j+1])
        min_f[i][j+1] = min(-OFFSET+10, min_f[i][j+1])
        max_f[i+1][j] = min(OFFSET-10, max_f[i+1][j])
        min_f[i+1][j] = min(-OFFSET+10, min_f[i+1][j])

        for k in range(OFFSET + min_f[i][j] - 1, OFFSET + max_f[i][j] + 1):
            if dp[i][j][k] == 0:
                continue
            # Move right
            dp[i][j+1][k+diffr] = 1
            dp[i][j+1][k-diffr] = 1
            # Move down
            dp[i+1][j][k+diffd] = 1
            dp[i+1][j][k-diffd] = 1
ans = 10**9
for i, item in enumerate(dp[h-1][w-1]):
    if item == 1:
        ans = min(ans, abs(i - OFFSET))
print(ans)