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
from collections import deque
def input(): return sys.stdin.readline().strip()


def main():
    H, W = map(int, input().split())
    A = []
    for _ in range(H):
        A.append(list(map(int, input().split())))
    B = []
    for _ in range(H):
        B.append(list(map(int, input().split())))
    
    """
    明らかなdp臭。
        dp[i][j] = (マス(0, 0)から(i, j)に進むときの偏りとしてありうるものの集合)
    とおく。(0<=i<=H-1, 0<=j<=W-1, 0<=d<=80)
    """

    dp = [[set([]) for _ in range(W)] for _ in range(H)]
    dp[0][0].add(abs(A[0][0] - B[0][0]))
    for i in range(1, H):
        diff = A[i][0] - B[i][0]
        for val in dp[i - 1][0]:
            dp[i][0].add(abs(val + diff))
            dp[i][0].add(abs(val - diff))
    for j in range(1, W):
        diff = A[0][j] - B[0][j]
        for val in dp[0][j - 1]:
            dp[0][j].add(abs(val + diff))
            dp[0][j].add(abs(val - diff))

    for i in range(1, H):
        for j in range(1, W):
            diff = A[i][j] - B[i][j]
            for val in dp[i - 1][j]:
                dp[i][j].add(abs(val + diff))
                dp[i][j].add(abs(val - diff))
            for val in dp[i][j - 1]:
                dp[i][j].add(abs(val + diff))
                dp[i][j].add(abs(val - diff))
    
    print(min(dp[H - 1][W - 1]))


   


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
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 = dict()
c = A[0][0]-B[0][0]
dp[(0, 0)] = {c, -c}
lim = 160 * 80

for i in range(H):
    for j in range(W):
        if i == j == 0:
            continue
        c = abs(A[i][j]-B[i][j])
        d = set()
        if i > 0:
            d |= {x + c for x in dp[(i - 1, j)] if x + c < lim}
            d |= {x - c for x in dp[(i - 1, j)] if x - c > -lim}
        if j > 0:
            d |= {x + c for x in dp[(i, j - 1)] if x + c < lim}
            d |= {x - c for x in dp[(i, j - 1)] if x - c > -lim}
        dp[(i, j)] = d

ans = min(abs(x) for x in dp[H - 1, W - 1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
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 = [[set() for _ in range(W)] for _ in range(H)]
dp[0][0].add(A[0][0] - B[0][0])
dp[0][0].add(B[0][0] - A[0][0])
lim = 160 * 80 // 2

for i in range(H):
    for j in range(W):
        c = abs(A[i][j]-B[i][j])
        if i > 0:
            dp[i][j] |= {x + c for x in dp[i - 1][j] if x + c <= lim}
            dp[i][j] |= {x - c for x in dp[i - 1][j] if x - c >= -lim}
        if j > 0:
            dp[i][j] |= {x + c for x in dp[i][j - 1] if x + c <= lim}
            dp[i][j] |= {x - c for x in dp[i][j - 1] if x - c >= -lim}

ans = min(abs(x) for x in dp[-1][-1])
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)]
d = [[0 for j in range(w)] for i in range(h)]
for i in range(h):
    for j in range(w):
        d[i][j] = abs(a[i][j]-b[i][j])

dp = [[0 for _ in range(6400)] for _ in range(h*w)]
dp[0][d[0][0]]=1

for i in range(h*w):
    nowh,noww = divmod(i,w)
    for k in range(6400):
        if not dp[nowh*w + noww][k]==1:
            continue
        nxth,nxtw=nowh+1, noww+1
        if nxtw<w:
            if k+d[nowh][nxtw] < 6400:
                dp[nowh*w + nxtw][k+d[nowh][nxtw]] = 1
            dp[nowh*w + nxtw][abs(k-d[nowh][nxtw])] = 1
        if nxth<h:
            if k+ d[nxth][noww]< 6400:
                dp[nxth*w + noww][k+d[nxth][noww]] = 1
            dp[nxth*w + noww][abs(k-d[nxth][noww])] = 1


for k in range(6400):
    if dp[-1][k]==1:
        print(k)
        exit()

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

dp = [[0 for _ in range(6400)] for _ in range(h*w)]
dp[0][d[0][0]]=1

for i in range(h*w):
    nowh,noww = divmod(i,w)
    for k in range(6400):
        if not dp[nowh*w + noww][k]==1:
            continue
        nxth,nxtw=nowh+1, noww+1
        if nxtw<w:
            if k+d[nowh][nxtw] < 6400:
                dp[nowh*w + nxtw][k+d[nowh][nxtw]] = 1
            dp[nowh*w + nxtw][abs(k-d[nowh][nxtw])] = 1
        if nxth<h:
            if k+ d[nxth][noww]< 6400:
                dp[nxth*w + noww][k+d[nxth][noww]] = 1
            dp[nxth*w + noww][abs(k-d[nxth][noww])] = 1


for k in range(6400):
    if dp[-1][k]==1:
        print(k)
        exit()

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

dp = [[0 for _ in range(6400)] for _ in range(h*w)]
dp[0][d[0][0]]=1

for i in range(h*w):
    nowh,noww = divmod(i,w)
    for k in range(6400):
        if not dp[nowh*w + noww][k]==1:
            continue
        nxth,nxtw=nowh+1, noww+1
        if nxtw<w:
            nxt=d[nowh][nxtw]
            if k+nxt < 6400:
                dp[nowh*w + nxtw][k+nxt] = 1
            dp[nowh*w + nxtw][abs(k-nxt)] = 1
        if nxth<h:
            nxt=d[nxth][noww]
            if k+nxt < 6400:
                dp[nxth*w + noww][k+nxt] = 1
            dp[nxth*w + noww][abs(k-nxt)] = 1


for k in range(6400):
    if dp[-1][k]==1:
        print(k)
        exit()

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

dp = [[0 for _ in range(6400)] for _ in range(h*w)]
dp[0][d[0][0]]=1

for i in range(h*w):
    nowh,noww = divmod(i,w)
    for k in range(6400):
        if not dp[nowh*w + noww][k]==1:
            continue
        nxth,nxtw=nowh+1, noww+1
        if nxtw<w:
            nxt=d[nowh][nxtw]
            if k+nxt < 6400:
                dp[nowh*w + nxtw][k+nxt] = 1
            dp[nowh*w + nxtw][abs(k-nxt)] = 1
        if nxth<h:
            nxt=d[nxth][noww]
            if k+nxt < 6400:
                dp[nxth*w + noww][k+nxt] = 1
            dp[nxth*w + noww][abs(k-nxt)] = 1


for k in range(6400):
    if dp[-1][k]==1:
        print(k)
        exit()

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)]
d=[]
for i in range(h):
    lis=[]
    for j in range(w):
        lis.append(abs(a[i][j]-b[i][j]))
    d.append(lis)

dp = [[0 for _ in range(6400)] for _ in range(h*w)]
dp[0][d[0][0]]=1

for i in range(h*w):
    nowh,noww = divmod(i,w)
    for k in range(6400):
        if not dp[nowh*w + noww][k]==1:
            continue
        nxth,nxtw=nowh+1, noww+1
        if nxtw<w:
            nxt=d[nowh][nxtw]
            if k+nxt < 6400:
                dp[nowh*w + nxtw][k+nxt] = 1
            dp[nowh*w + nxtw][abs(k-nxt)] = 1
        if nxth<h:
            nxt=d[nxth][noww]
            if k+nxt < 6400:
                dp[nxth*w + noww][k+nxt] = 1
            dp[nxth*w + noww][abs(k-nxt)] = 1


for k in range(6400):
    if dp[-1][k]==1:
        print(k)
        exit()

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)]
d=[]
for i in range(h):
    lis=[]
    for j in range(w):
        lis.append(abs(a[i][j]-b[i][j]))
    d.append(lis)

dp = [[[0 for _ in range(80*(h+w))] for _ in range(w)] for _ in range(h)]
dp = [[0 for _ in range(6400)] for _ in range(h*w)]
dp[0][d[0][0]]=1

for i in range(h*w):
    nowh,noww = divmod(i,w)
    for k in range(6400):
        if not dp[nowh*w + noww][k]==1:
            continue
        nxth,nxtw=nowh+1, noww+1
        if nxtw<w:
            nxt=d[nowh][nxtw]
            if k+nxt < 6400:
                dp[nowh*w + nxtw][k+nxt] = 1
            dp[nowh*w + nxtw][abs(k-nxt)] = 1
        if nxth<h:
            nxt=d[nxth][noww]
            if k+nxt < 6400:
                dp[nxth*w + noww][k+nxt] = 1
            dp[nxth*w + noww][abs(k-nxt)] = 1


for k in range(6400):
    if dp[-1][k]==1:
        print(k)
        exit()

Submission status: Time Limit Exceeded

Solution code:
import sys
def main():
  input=sys.stdin.readline
  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)]
  cnt=0
  for i in range(h):
    for j in range(w):
      cnt=max(cnt,abs(a[i][j]-b[i][j]))
  m=cnt*(h+w)
  dp=[[[0]*(m+1) for i in range(w)] for j in range(h)]
  dp[0][0][abs(a[0][0]-b[0][0])]=1
  for i in range(h):
    for j in range(w):
      for k in range(m+1):
        if dp[i][j][k]:
          if i<h-1:
            if abs(k+a[i+1][j]-b[i+1][j])<=m:
              dp[i+1][j][abs(k+a[i+1][j]-b[i+1][j])]=1
            if abs(k+b[i+1][j]-a[i+1][j])<=m:
              dp[i+1][j][abs(k+b[i+1][j]-a[i+1][j])]=1
          if j<w-1:
            if abs(k+a[i][j+1]-b[i][j+1])<=m:
              dp[i][j+1][abs(k+a[i][j+1]-b[i][j+1])]=1
            if abs(k+b[i][j+1]-a[i][j+1])<=m:
              dp[i][j+1][abs(k+b[i][j+1]-a[i][j+1])]=1
  for i in range(m+1):
    if dp[h-1][w-1][i]:
      return print(i)
if __name__=='__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
import sys
def main():
  input=sys.stdin.readline
  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)]
  m=80*(h+w)
  dp=[[[False]*(m+1) for i in range(w)] for j in range(h)]
  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(m+1):
        if dp[i][j][k]:
          if i<h-1:
            if abs(k+a[i+1][j]-b[i+1][j])<=m:
              dp[i+1][j][abs(k+a[i+1][j]-b[i+1][j])]=True
            if abs(k+b[i+1][j]-a[i+1][j])<=m:
              dp[i+1][j][abs(k+b[i+1][j]-a[i+1][j])]=True
          if j<w-1:
            if abs(k+a[i][j+1]-b[i][j+1])<=m:
              dp[i][j+1][abs(k+a[i][j+1]-b[i][j+1])]=True
            if abs(k+b[i][j+1]-a[i][j+1])<=m:
              dp[i][j+1][abs(k+b[i][j+1]-a[i][j+1])]=True
  for i in range(m+1):
    if dp[h-1][w-1][i]:
      return print(i)
if __name__=='__main__':
  main()

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 = []
# red - blue
for i in range(h):
    dp.append([])
    for j in range(w):
        dp[i].append([False]*(80*160 + 1))

for i in range(h):
    for j in range(w):
        delta = abs(A[i][j] - B[i][j])
        if i == j == 0:
            dp[i][j][delta] = True
        else:
            if i != 0:
                for root,flag in enumerate(dp[i-1][j]):
                    if flag:
                        dp[i][j][root + delta] = True
                        dp[i][j][abs(root - delta)] = True
                    if root >= (i+j+2)*80:
                        break
            if j != 0:
                for root,flag in enumerate(dp[i][j-1]):
                    if flag:
                        dp[i][j][root + delta] = True
                        dp[i][j][abs(root - delta)] = True
                    if root >= (i+j+2)*80:
                        break
print(dp[h-1][w-1].index(True))

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 = []
# A - B
for i in range(h):
    dp.append([])
    for j in range(w):
        dp[i].append(set())

for i in range(h):
    for j in range(w):
        a = A[i][j]
        b = B[i][j]
        if i == j == 0:
            dp[i][j] = set([a-b, b-a])
        else:
            if i != 0:
                for root in dp[i-1][j]:
                    dp[i][j].add(root + a - b)
                    dp[i][j].add(root + b - a)
            if j != 0:
                for root in dp[i][j-1]:
                    dp[i][j].add(root + a - b)
                    dp[i][j].add(root + b - a)
ans = 80*160
for delta in dp[h-1][w-1]:
    ans = min(ans, abs(delta))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w = list(map(int, readline().split()))
    a = [list(map(int, readline().split())) for _ in range(h)]
    b = [list(map(int, readline().split())) for _ in range(h)]

    diff = [[abs(an - bn) for an, bn in zip(arow, brow)] for arow, brow in zip(a, b)]

    dp = [[set() for _ in range(w)] for _ in range(h)]
    dp[0][0].add(diff[0][0])

    from itertools import product

    for row, col in product(range(h),range(w)):
        curset = set()
        prevset = set()
        curdiff = diff[row][col]

        if row - 1 >= 0:
            prevset |= dp[row - 1][col]
        if col - 1 >= 0:
            prevset |= dp[row][col - 1]

        for num in prevset:
            curset.add(num + curdiff)
            curset.add(abs(num - curdiff))
        dp[row][col] |= curset

    cand = list(dp[h - 1][w - 1])

    print(min(cand))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w = list(map(int, readline().split()))
    a = [list(map(int, readline().split())) for _ in range(h)]
    b = [list(map(int, readline().split())) for _ in range(h)]

    diff = [[abs(an - bn) for an, bn in zip(arow, brow)] for arow, brow in zip(a, b)]

    dp = [[set() for _ in range(w)] for _ in range(h)]
    dp[0][0].add(diff[0][0])

    from collections import deque
    que = deque()
    que.append((1, 0))
    que.append((0, 1))

    seen = [[False] * w for _ in range(h)]

    while que:
        row, col = que.popleft()

        if row + 1 < h:
            if not seen[row + 1][col]:
                seen[row + 1][col] = True
                que.append((row + 1, col))
        if col + 1 < w:
            if not seen[row][col + 1]:
                seen[row][col + 1] = True
                que.append((row, col + 1))

        curset = set()
        prevset = set()
        curdiff = diff[row][col]

        if row - 1 >= 0:
            prevset |= dp[row - 1][col]
        if col - 1 >= 0:
            prevset |= dp[row][col - 1]

        for num in prevset:
            curset.add(num + curdiff)
            curset.add(abs(num - curdiff))
        dp[row][col] |= curset

    cand = list(dp[h - 1][w - 1])

    print(min(cand))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w = list(map(int, readline().split()))
    a = [list(map(int, readline().split())) for _ in range(h)]
    b = [list(map(int, readline().split())) for _ in range(h)]

    diff = [[abs(an - bn) for an, bn in zip(arow, brow)] for arow, brow in zip(a, b)]

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

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

    from collections import deque
    que = deque()
    que.append((0, 0))

    seen = [[False] * w for _ in range(h)]

    while que:
        row, col = que.popleft()

        if row + 1 < h:
            if not seen[row + 1][col]:
                seen[row + 1][col] = True
                que.append((row + 1, col))

            for num in dp[row][col]:
                dp[row + 1][col].add(num + diff[row + 1][col])
                dp[row + 1][col].add(abs(num - diff[row + 1][col]))

        if col + 1 < w:
            if not seen[row][col + 1]:
                seen[row][col + 1] = True
                que.append((row, col + 1))

            for num in dp[row][col]:
                dp[row][col + 1].add(num + diff[row][col + 1])
                dp[row][col + 1].add(abs(num - diff[row][col + 1]))

    cand = list(dp[h - 1][w - 1])

    print(min(cand))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w = list(map(int, readline().split()))
    a = [list(map(int, readline().split())) for _ in range(h)]
    b = [list(map(int, readline().split())) for _ in range(h)]

    diff = [[abs(an - bn) for an, bn in zip(arow, brow)] for arow, brow in zip(a, b)]

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

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

    from collections import deque
    que = deque()
    que.append((0, 0))

    while que:
        row, col = que.popleft()

        if row + 1 < h:
            que.append((row + 1, col))
            for num in dp[row][col]:
                dp[row + 1][col].add(num + diff[row + 1][col])
                dp[row + 1][col].add(abs(num - diff[row + 1][col]))

        if col + 1 < w:
            que.append((row, col + 1))
            for num in dp[row][col]:
                dp[row][col + 1].add(num + diff[row][col + 1])
                dp[row][col + 1].add(abs(num - diff[row][col + 1]))

    cand = list(dp[h - 1][w - 1])

    print(min(cand))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w = list(map(int, readline().split()))
    a = [list(map(int, readline().split())) for _ in range(h)]
    b = [list(map(int, readline().split())) for _ in range(h)]

    diff = [[abs(an - bn) for an, bn in zip(arow, brow)] for arow, brow in zip(a, b)]

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

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

    from collections import deque
    que = deque()
    que.append((0, 0))

    while que:
        row, col = que.popleft()
        for num in dp[row][col]:
            if row + 1 < h:
                dp[row + 1][col].add(num + diff[row + 1][col])
                dp[row + 1][col].add(abs(num - diff[row + 1][col]))
                que.append((row + 1, col))
            if col + 1 < w:
                dp[row][col + 1].add(num + diff[row][col + 1])
                dp[row][col + 1].add(abs(num - diff[row][col + 1]))
                que.append((row, col + 1))

    cand = list(dp[h - 1][w - 1])

    print(min(cand))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(300000)

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')


H, W = MI()
A = [LMI() for _ in range(H)]
B = [LMI() for _ in range(H)]

max_k = 12641
# dp[i][j][k] := マス(i, j)までの経路で偏りがkになることがあるか
dp = [[[False] * max_k for _ in range(W)] for _ in range(H)]
dp[0][0][abs(A[0][0] - B[0][0])] = True

for i in range(H):
    for j in range(W):
        p = abs(A[i][j] - B[i][j])
        for k in range(max_k):
            if i > 0:
                if abs(k - p) < max_k:
                    dp[i][j][k] |= dp[i - 1][j][abs(k - p)]
                if k + p < max_k:
                    dp[i][j][k] |= dp[i - 1][j][k + p]
            if j > 0:
                if abs(k - p) < max_k:
                    dp[i][j][k] |= dp[i][j - 1][abs(k - p)]
                if k + p < max_k:
                    dp[i][j][k] |= dp[i][j - 1][k + p]
print(dp[H - 1][W - 1].index(True))

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)]

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

dp = [[0] * 9600 for _ in range(w*h)]
for i in range(h):
    for j in range(w):
        min_ = max(0, 3200 - min(i+j, 160-i-j)*80)
        max_ = min(9599, 3200 + min(i+j, 160-i-j)*80)
        a_tmp = a[i][j]
        if(i==0)&(j==0):
            dp[i*w+j][3200+a_tmp] += 1
            dp[i*w+j][3200-a_tmp] += 1
        elif(i==0):
            for k in range(min_, max_+1):
                if(k+a_tmp < 9600):
                    dp[i*w+j][k+a_tmp] += dp[i*w+j-1][k]
                if(k-a_tmp >= 0):
                    dp[i*w+j][k-a_tmp] += dp[i*w+j-1][k]
        elif(j==0):
            for k in range(min_, max_+1):
                if(k+a_tmp < 9600):
                    dp[i*w+j][k+a_tmp] += dp[i*w+j-w][k]
                if(k+a_tmp >= 0):
                    dp[i*w+j][k-a_tmp] += dp[i*w+j-w][k]
        else:
            for k in range(min_, max_+1):
                if(k+a_tmp < 9600):
                    dp[i*w+j][k+a_tmp] += dp[i*w+j-1][k]
                    dp[i*w+j][k+a_tmp] += dp[i*w+j-w][k]
                if(k+a_tmp >= 0):
                    dp[i*w+j][k-a_tmp] += dp[i*w+j-1][k]
                    dp[i*w+j][k-a_tmp] += dp[i*w+j-w][k]

ans = 3200
for i in range(3100, 3300):
    if(dp[-1][i] > 0):
        ans = min(ans, abs(i-3200))

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)]

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

dp = [[0] * 9600 for _ in range(w)]
for i in range(h):
    for j in range(w):
        min_ = max(0, 3200 - min(i+j, 160-i-j)*80)
        max_ = min(9599, 3200 + min(i+j, 160-i-j)*80)
        a_tmp = a[i][j]
        if(i==0)&(j==0):
            dp[j][3200+a_tmp] += 1
            dp[j][3200-a_tmp] += 1
        elif(i==0):
            for k in range(min_, max_+1):
                if(k+a_tmp < 9600):
                    dp[j][k+a_tmp] += dp[j-1][k]
                if(k-a_tmp >= 0):
                    dp[j][k-a_tmp] += dp[j-1][k]
        elif(j==0):
            tmp = [0] * 9600
            for k in range(min_, max_+1):
                if(k+a_tmp < 9600):
                    tmp[k+a_tmp] += dp[j][k]
                if(k+a_tmp >= 0):
                    tmp[k-a_tmp] += dp[j][k]
            dp[j] = tmp[::]
        else:
            tmp = [0] * 9600
            for k in range(min_, max_+1):
                if(k+a_tmp < 9600):
                    tmp[k+a_tmp] += dp[j-1][k]
                    tmp[k+a_tmp] += dp[j][k]
                if(k+a_tmp >= 0):
                    tmp[k-a_tmp] += dp[j-1][k]
                    tmp[k-a_tmp] += dp[j][k]
            dp[j] = tmp[::]

ans = 3200
for i in range(3100, 3300):
    if(dp[-1][i] > 0):
        ans = min(ans, abs(i-3200))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

mod = 10**9+7 #出力の制限

# a = cmb(n,r)
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

def ans():
    H,W = m()

    a = []

    for i in range(H):
        a.append(l())

    ma = 0
    b = []
    for i in range(H):
        b.append(l())
        for j in range(W):
            ma = max(ma,abs(a[i][j]-b[i][j]))
    ma += 1
    dp = [[[0 for i in range(ma*(min(H,W)))]for j in range(W)] for k in range(H)]

    for i in range(H):
        for j in range(W):
            po = abs(a[i][j] - b[i][j])
            if i == 0 and j == 0:
                dp[0][0][po] = 1
            elif i == 0:
                for k in range(ma*(min(H,W))):
                    if abs(k + po) < ma*min(H,W):
                        dp[i][j][abs(k + po)] = max(dp[i][j-1][k],dp[i][j][abs(k + po)])
                    if abs(k - po) < ma*min(H,W):
                        dp[i][j][abs(k - po)] = max(dp[i][j-1][k],dp[i][j][abs(k - po)])
            elif j == 0:
                for k in range(ma*(min(H,W))):
                    if abs(k + po) < ma*min(H,W):
                        dp[i][j][abs(k + po)] = max(dp[i-1][j][k],dp[i][j][abs(k + po)])
                    if abs(k - po) < ma*min(H,W):
                        dp[i][j][abs(k - po)] = max(dp[i-1][j][k],dp[i][j][abs(k - po)])
            else:
                for k in range(ma*(min(H,W))):
                    if abs(k + po) < ma*min(H,W):
                        dp[i][j][abs(k + po)] = max(dp[i][j-1][k],dp[i-1][j][k],dp[i][j][abs(k + po)])
                    if abs(k - po) < ma*min(H,W):
                        dp[i][j][abs(k - po)] = max(dp[i][j-1][k],dp[i-1][j][k],dp[i][j][abs(k - po)])

    for i in range(ma*min(H,W)):
        if dp[-1][-1][i] == 1:
            print(i)
            exit()




if __name__ == "__main__":
    ans()

Submission status: Time Limit Exceeded

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

mod = 10**9+7 #出力の制限

# a = cmb(n,r)
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

def ans():
    H,W = m()

    a = []

    for i in range(H):
        a.append(l())

    ma = 0
    b = []
    for i in range(H):
        b.append(l())
        for j in range(W):
            ma = max(ma,abs(a[i][j]-b[i][j]))
    ma += 1
    dp = [[[0 for i in range(ma*(min(H,W)))]for j in range(W)] for k in range(H)]

    for i in range(H):
        for j in range(W):
            if i == 0 and j == 0:
                dp[0][0][abs(a[0][0] - b[0][0])] = 1
            elif i == 0:
                for k in range(ma*(min(H,W))):
                    if abs(k + abs(a[i][j] - b[i][j])) < ma*min(H,W):
                        dp[i][j][abs(k + abs(a[i][j] - b[i][j]))] = max(dp[i][j-1][k],dp[i][j][abs(k + abs(a[i][j] - b[i][j]))])
                    if abs(k - abs(a[i][j] - b[i][j])) < ma*min(H,W):
                        dp[i][j][abs(k - abs(a[i][j] - b[i][j]))] = max(dp[i][j-1][k],dp[i][j][abs(k - abs(a[i][j] - b[i][j]))])
            elif j == 0:
                for k in range(ma*(min(H,W))):
                    if abs(k + abs(a[i][j] - b[i][j])) < ma*min(H,W):
                        dp[i][j][abs(k + abs(a[i][j] - b[i][j]))] = max(dp[i-1][j][k],dp[i][j][abs(k + abs(a[i][j] - b[i][j]))])
                    if abs(k - abs(a[i][j] - b[i][j])) < ma*min(H,W):
                        dp[i][j][abs(k - abs(a[i][j] - b[i][j]))] = max(dp[i-1][j][k],dp[i][j][abs(k - abs(a[i][j] - b[i][j]))])
            else:
                for k in range(ma*(min(H,W))):
                    if abs(k + abs(a[i][j] - b[i][j])) < ma*min(H,W):
                        dp[i][j][abs(k + abs(a[i][j] - b[i][j]))] = max(dp[i][j-1][k],dp[i-1][j][k],dp[i][j][abs(k + abs(a[i][j] - b[i][j]))])
                    if abs(k - abs(a[i][j] - b[i][j])) < ma*min(H,W):
                        dp[i][j][abs(k - abs(a[i][j] - b[i][j]))] = max(dp[i][j-1][k],dp[i-1][j][k],dp[i][j][abs(k - abs(a[i][j] - b[i][j]))])

    for i in range(ma*min(H,W)):
        if dp[-1][-1][i] == 1:
            print(i)
            exit()




if __name__ == "__main__":
    ans()