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)]
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 -160*80<=dp[i][j][k]+c[i+1][j]<=160*80:
          l.append(dp[i][j][k]+c[i+1][j])
        if -160*80<=l[k]-c[i+1][j]<=160*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 -160*80<=dp[i][j][k]+c[i][j+1]<=160*80:
          l.append(dp[i][j][k]+c[i][j+1])
        if -160*80<=dp[i][j][k]-c[i][j+1]<=160*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: 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)]

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):
    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:
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 -160*80<=dp[i][j][k]+c[i+1][j]<=160*80:
          l.append(dp[i][j][k]+c[i+1][j])
        if -160*80<=l[k]-c[i+1][j]<=160*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 -160*80<=dp[i][j][k]+c[i][j+1]<=160*80:
          l.append(dp[i][j][k]+c[i][j+1])
        if -160*80<=dp[i][j][k]-c[i][j+1]<=160*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: 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), abs(item - n)}
                if w < W - 1:
                    n = grid[h][w+1]
                    dist[h][w+1] |= {abs(item + n), abs(item - n)}
    
    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:
import sys

read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines

mod=10**9+7
# rstrip().decode('utf-8')
# map(int,input().split())
import numpy as np

def main():
	h,w=map(int,input().split())
	AB=np.array(read().split(), np.int64)
	
	
	A=AB[:h*w]
	B=AB[h*w:]
	
	A=np.reshape(A, (h,w))
	B = np.reshape(B, (h, w))
	
	G=abs(A-B)
	
	li=[[[]for i in range(w)] for j in range(h)]
	for i in range(h):
		for j in range(w):
			if i==j==0:
				li[i][j].append(G[i][j])
			elif i==0:
				for k in li[i][j-1]:
					li[i][j].append(abs(k-G[i][j]))
					li[i][j].append(abs(k + G[i][j]))
			elif j==0:
				for k in li[i-1][j]:
					li[i][j].append(abs(k-G[i][j]))
					li[i][j].append(abs(k + G[i][j]))
			else:
				for k in li[i-1][j]:
					li[i][j].append(abs(k-G[i][j]))
					li[i][j].append(abs(k + G[i][j]))
				for k in li[i][j-1]:
					li[i][j].append(abs(k-G[i][j]))
					li[i][j].append(abs(k + G[i][j]))
			s=set(li[i][j])
			li[i][j]=sorted(list(s))
			
	print(min(li[h-1][w-1]))
	
if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

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 10**9
    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: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
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 = 80*159+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]:
                if abs(v+C[y][x]) < VMAX:
                    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]:
                if abs(v+C[y][x]) < VMAX:
                    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:
Y = 80 * 160 + 1
X = Y * 2

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

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

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

values = None
for h in range(H):
	new_values = []
	for w in range(W):
		prev_values = [False] * X
		if h == 0 and w == 0:
			prev_values[0 + Y] = True
		else:
			if w > 0:
				l = new_values[w - 1]
				for i in range(X):
					if l[i]:
						prev_values[i] = True
			if h > 0:
				l = values[w]
				for i in range(X):
					if l[i]:
						prev_values[i] = True
		value = A_list[h][w] - B_list[h][w]
		new_set = [False] * X
		for v in range(X):
			if prev_values[v]:
				new_set[v - value] = True
				new_set[v + value] = True
		new_values.append(new_set)
	values = new_values
#	print(values)

min = None

for v in range(X):
	if values[W - 1][v]:
		v2 = abs(v - Y)
		if min == None or min > v2:
			min = v2

print(min)

Submission status: Time Limit Exceeded

Solution code:
#設定
import sys
input = sys.stdin.buffer.readline

#ライブラリインポート
from collections import defaultdict

#入力受け取り
def getlist():
	return list(map(int, input().split()))

#処理内容
def main():
	H, W = getlist()
	A = []
	for i in range(H):
		a = getlist()
		A.append(a)
	B = []
	for i in range(H):
		b = getlist()
		B.append(b)

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

	DP = [[[0] * 25601 for i in range(W)] for j in range(H)]
	DP[0][0][A[0][0] + 12800] = 1
	for i in range(H):
		for j in range(W):
			for k in range(25601):
				if DP[i][j][k] == 1:
					if j < W - 1:
						DP[i][j + 1][k + A[i][j + 1]] = 1
						DP[i][j + 1][k - A[i][j + 1]] = 1
					if i < H - 1:
						DP[i + 1][j][k + A[i + 1][j]] = 1
						DP[i + 1][j][k - A[i + 1][j]] = 1

	ans = 1000000
	for i in range(25601):
		if DP[H - 1][W - 1][i] == 1:
			ans = min(ans, abs(12800 - 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)]

m = (h+w)*80
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]:
        if e <= m:
            sets[i][0].add(e + c[i][0])
            sets[i][0].add(abs(e - c[i][0]))
for i in range(1, w):
    for e in sets[0][i - 1]:
        if e <= m:
            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]:
            if e <= m:
                sets[i][j].add(e+c[i][j])
                sets[i][j].add(abs(e - c[i][j]))
        for e in sets[i][j-1]:
            if e <= m:
                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 = [[] for i in range(H)]
B = [[] for i in range(H)]

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

D = [[abs(A[i][j]) - abs(B[i][j]) for j in range(W)] for i in range(H)]
R = 160*160
dp = [[[False for k in range(R)] for j in range(W)] for i in range(H)]
dp[0][0][R//2 - D[0][0]] = True
dp[0][0][R//2 + D[0][0]] = True
for i in range(H):
	for j in range(W):
		for n in range(R):
			if not dp[i][j][n]:
				continue
			if j != W-1:
				d = D[i][j+1]
				dp[i][j+1][n+d] = True
				dp[i][j+1][n-d] = True
			if i != H-1:
				d = D[i+1][j]
				dp[i+1][j][n+d] = True
				dp[i+1][j][n-d] = True

h,w = H-1, W-1
M = R // 2
for i in range(160*80):
	if dp[h][w][M - i] or dp[h][w][M - i]:
		print(i)
		exit()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def calc_min_abs(inA, inB):
  ans = float('inf')

  for i in range(2**(len(inA))):
    flags = bin(i)[2:].zfill(len(inA))
    val1,val2 = 0,0
    for i in range(len(flags)):
      if flags[i] == '0':
        val1 += inA[i]
        val2 += inB[i]
      else:
        val1 += inB[i]
        val2 += inA[i]
    ans = min(ans,abs(val1-val2))
  return ans

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

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
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)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    h,w = LI()
    a = LIR(h)
    b = LIR(h)
    for i in range(h):
        for j in range(w):
            a[i][j] -= b[i][j]
            if a[i][j] < 0:
                a[i][j] *= -1
    d = [(0,1),(1,0)]
    Ma = [[160*min((x+y+1), (h+w-x-y-1)) for x in range(w)] for y in range(h)]
    f = [[[0 for i in range(-Ma[y][x], Ma[y][x]+1)] for x in range(w)] for y in range(h)]
    f[0][0][a[0][0]] = 1
    for y in range(h):
        for x in range(w):
            for t in range(-Ma[y][x],Ma[y][x]+1):
                if not f[y][x][t]:
                    continue
                for dy,dx in d:
                    ny = y+dy
                    nx = x+dx
                    if 0 <= ny < h and 0 <= nx < w:
                        M = Ma[ny][nx]
                        m = -M
                        nt = t-a[ny][nx]
                        if m <= nt <= M:
                            f[ny][nx][nt] = 1
                        nt = t+a[ny][nx]
                        if m <= nt <= M:
                            f[ny][nx][nt] = 1
    ans = min([abs(i) for i in range(-Ma[h-1][w-1], Ma[h-1][w-1]+1) if f[h-1][w-1][i]])
    print(ans)
    return

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

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]:
                z = abs(x + y)
                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]:
                z = abs(x + y)
                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: Time Limit Exceeded

Solution code:
def main():
    h, w = map(int, input().split())

    xss = [[int(x) for x in input().split()] for _ in range(h)]
    yss = [[int(y) for y in input().split()] for _ in range(h)]
    uss = [[x - y for x, y in zip(xs, ys)] for xs, ys in zip(xss, yss)]

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

    dp[0][0].add(uss[0][0])
    dp[0][0].add(-uss[0][0])

    for i in range(1, w):
        x = dp[0][i]
        for d in dp[0][i-1]:
            x.add(d + uss[0][i])
            x.add(d - uss[0][i])
    for i in range(1, h):
        x = dp[i][0]
        for d in dp[i-1][0]:
            x.add(d + uss[i][0])
            x.add(d - uss[i][0])
    
    for i in range(1, h):
        for j in range(1, w):
            x = dp[i][j]
            for d in dp[i-1][j]:
                x.add(d + uss[i][j])
                x.add(d - uss[i][j])
            for d in dp[i][j-1]:
                x.add(d + uss[i][j])
                x.add(d - uss[i][j])
    ans = min(abs(d) for d in dp[-1][-1])
    print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
def LI(): return([int(x) for x in sys.stdin.readline().split()])
 
def main():
    H,W = LI()
    A = [LI() for _ in range(H)]
    B = [LI() for _ in range(H)]
    D = [[abs(A[h][w]-B[h][w]) for w in range(W)] for h in range(H)]
    dp = [[set() for w in range(W)] for h in range(H)]

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

    for h in range(H):
        for w in range(W):
            if(h>0):
                for s in dp[h-1][w]:
                    dp[h][w].add(abs(s-D[h][w]))
                    if s<=6400:
                        dp[h][w].add(s+D[h][w])
            if(w>0):
                for s in dp[h][w-1]:
                    dp[h][w].add(abs(s-D[h][w]))
                    if s<=6400:
                        dp[h][w].add(s+D[h][w])
    return(min(dp[H-1][W-1]))
 
if __name__ == "__main__":
    print(main())

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)]
for i in range(h):
    for j in range(w):
        C[i][j] = abs(A[i][j]-B[i][j])
 
V = [[2] * w for i in range(h)]
for i in range(h):
    V[i][0] -= 1
for i in range(w):
    V[0][i] -= 1
 
l = 6500
m = 0
 
M = [[[0] * l for i in range(w)] for j in range(h)]
N = [[0 for i in range(w)] for j in range(h)]
N[0][0] = C[0][0]
 
s = 0
Q = [[0, 0]]
 
M[0][0][C[0][0]] = 1
# M[0][0][m-C[0][0]] = 1
 
while len(Q) > s:
    i = Q[s][0]
    j = Q[s][1]
    if i+1 < h:
        for ii in range(min(N[i][j]+1, l)):
            if M[i][j][ii] == 1:
                if abs(ii+C[i+1][j]) < l:
                    M[i+1][j][abs(ii+C[i+1][j])] = 1
                if abs(ii-C[i+1][j]) < l:
                    M[i+1][j][abs(ii-C[i+1][j])] = 1
        V[i+1][j] -= 1
        # print(N[i+1][j], N[i][j] + C[i+1][j])
        N[i+1][j] = max(N[i+1][j], N[i][j] + C[i+1][j])
        if V[i+1][j]==0:
            Q.append([i+1,j])
    if j+1 < w:
        for ii in range(min(N[i][j]+1, l)):
            if M[i][j][ii] == 1:
                if abs(ii+C[i][j+1]) < l:
                    M[i][j+1][abs(ii+C[i][j+1])] = 1
                if abs(ii-C[i][j+1]) < l:
                    M[i][j+1][abs(ii-C[i][j+1])] = 1
        V[i][j+1] -= 1
        N[i][j+1] = max(N[i][j+1], N[i][j] + C[i][j+1])
        if V[i][j+1]==0:
            Q.append([i,j+1])
        
    
    s += 1
 
# print(M[-1][-1])
 
ans = 10**5
for i in range(len(M[-1][-1])):
    if M[-1][-1][i] == 1:
        ans = i
        break
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]:
                if k<=7000:
                    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]:
                if k<=7000:
                    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<=7000:
                    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 = [[int(a) for a in input().split()] for _ in range(H)]
B = [[int(a) for a in input().split()] for _ in range(H)]

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


dp = {}
dp[(0, 0)] = [L[0][0], -L[0][0]]
for i in range(1, W):
    dp[(0, i)] = []
    for k in dp[(0, i-1)]:
        dp[(0, i)].append(k+L[0][i])
        dp[(0, i)].append(k-L[0][i])
for i in range(1, H):
    dp[(i, 0)] = []
    for k in dp[(i-1, 0)]:
        dp[(i, 0)].append(k+L[i][0])
        dp[(i, 0)].append(k-L[i][0])
        
for i in range(1, H):
    for j in range(1, W):
        dp[(i, j)] = []
        if i != 0:
            for t in dp[(i-1, j)]:
                dp[(i, j)].append(t+L[i][j])
                dp[(i, j)].append(t-L[i][j])
        if j != 0:
            for t in dp[(i, j-1)]:
                dp[(i, j)].append(t+L[i][j])
                dp[(i, j)].append(t-L[i][j])
        if i-1 > 0 and j-1 > 0:
            dp.pop((i, j))
            
ans = 10**9
for k in dp[(H-1, W-1)]:
    ans = min(ans, abs(k))
    
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]:
                if abs(k+A[i][j]-B[i][j])<=(H+W-1)*20:
                    d[i][j].add(abs(k+A[i][j]-B[i][j]))
                if abs(-k+A[i][j]-B[i][j])<=(H+W-1)*20:
                    d[i][j].add(abs(-k+A[i][j]-B[i][j]))
            for k in d[i][j-1]:
                if abs(k+A[i][j]-B[i][j])<=(H+W-1)*20:
                    d[i][j].add(abs(k+A[i][j]-B[i][j]))
                if abs(-k+A[i][j]-B[i][j])<=(H+W-1)*20:
                    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 = i
        if ans>now:
            ans = now
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=[[set() for i in range(W+1)] for j in range(H+1)]
d[1][1].add(A[0][0]-B[0][0])
d[1][1].add(B[0][0]-A[0][0])
for h in range(H):
    for w in range(W):
        x=A[h][w]-B[h][w]
        for y in d[h][w+1]:
            d[h+1][w+1].add((y+x)%(80*H*W))
            d[h+1][w+1].add((y-x)%(80*H*W))
        for y in d[h+1][w]:
            d[h+1][w+1].add((y+x)%(80*H*W))
            d[h+1][w+1].add((y-x)%(80*H*W))
for i in range(80*H*W):
    if i in d[H][W] or -i in d[H][W]:
        print(i)
        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)]
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 * 70 + 1
dp = [[False]*n for i in range(h*w)]
dp[0][diff[0][0]] = True

for k in range(h*w):
    for cnt in range(n):
        if dp[k][cnt]:
                i = k // w
                j = k % w
                tmp1 = diff[i+1][j]
                tmp2 = diff[i][j+1]
                if i+1 < h:
                    dp[k + w][abs(cnt - tmp1)] = True
                    if cnt + tmp1 < n:
                        dp[k + w][cnt + tmp1] = True

                if j+1 < w:
                    dp[k + 1][abs(cnt - tmp2)] = True 
                    if cnt + tmp2 < n:
                        dp[k + 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:
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 = [[] for i in range(H)]
for i in range(H):
    for j in range(W):
        
        C[i].append({})

#print (C)

for i in range(H):

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

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

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

#print (C)

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

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

        for k in C[i-1][j]:

            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
        for k in C[i][j-1]:
            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 C[-1][-1]:

    ans = min(ans,i)
    
print (ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    h, w = map(int, input().split())

    xss = [[int(x) for x in input().split()] for _ in range(h)]
    yss = [[int(y) for y in input().split()] for _ in range(h)]
    uss = [[x - y for x, y in zip(xs, ys)] for xs, ys in zip(xss, yss)]

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

    dp[0][0].add(uss[0][0])
    dp[0][0].add(-uss[0][0])

    for i in range(1, w):
        x = dp[0][i]
        for d in dp[0][i-1]:
            x.add(d + uss[0][i])
            x.add(d - uss[0][i])
    for i in range(1, h):
        x = dp[i][0]
        for d in dp[i-1][0]:
            x.add(d + uss[i][0])
            x.add(d - uss[i][0])
    
    for i in range(1, h):
        for j in range(1, w):
            x = dp[i][j]
            for d in dp[i-1][j]:
                x.add(d + uss[i][j])
                x.add(d - uss[i][j])
            for d in dp[i][j-1]:
                x.add(d + uss[i][j])
                x.add(d - uss[i][j])
    ans = sorted(abs(d) for d in dp[-1][-1])
    print(ans[0])

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=[[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<=7000:
                    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]:
                if abs(k+A[i][j]-B[i][j])<=(H+W-1)*80+1:
                    d[i][j].add(abs(k+A[i][j]-B[i][j]))
                if abs(-k+A[i][j]-B[i][j])<=(H+W-1)*80+1:
                    d[i][j].add(abs(-k+A[i][j]-B[i][j]))
            for k in d[i][j-1]:
                if abs(k+A[i][j]-B[i][j])<=(H+W-1)*80+1:
                    d[i][j].add(abs(k+A[i][j]-B[i][j]))
                if abs(-k+A[i][j]-B[i][j])<=(H+W-1)*80+1:
                    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 = i
        if ans>now:
            ans = now
print(ans)