Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

words = lambda t : list(map(t, input().split()))

def getNext(xs, i):
    if i == len(xs)-1:
        return 0
    else:
        return i+1

def getPrev(xs, i):
    if i == 0:
        return len(xs)-1
    else:
        return i-1

n = int(input())
a = words(int)
b = words(int)

import queue
q = queue.Queue()

def verify(i):
    if b[i] != a[i] and b[i] - (b[getNext(b,i)] + b[getPrev(b,i)]) >= a[i]:
        return True
    else:
        return False

for i in range(len(b)):
    if verify(i):
        q.put(i)

ans = 0
succeed = True
while not q.empty():
    i = q.get()
    #print(i, b)
    d = b[getNext(b,i)] + b[getPrev(b,i)]
    if b[i] % d == a[i] % d:
        ans += b[i] // d - (a[i] // d)
        b[i] = a[i]
    else:
        ans += b[i] // d
        b[i] = b[i] % d
    if b[i] < a[i]:
        succeed = False
        break
    if verify(getNext(b,i)):
        q.put(getNext(b,i))
    if verify(getPrev(b,i)):
        q.put(getPrev(b,i))

for i in range(len(b)):
    if a[i] != b[i]:
        succeed = False
        break

if succeed:
    print(ans)
else:
    print(-1)


### FIXED CODE ###

words = lambda t : list(map(t, input().split()))



n = int(input())
a = words(int)
b = words(int)

def getNext(i):
    if i == n-1:
        return 0
    else:
        return i+1

def getPrev(i):
    if i == 0:
        return n-1
    else:
        return i-1

from collections import deque
q = deque()

def verify(i):
    if b[i] != a[i] and b[i] - (b[getNext(i)] + b[getPrev(i)]) >= a[i]:
        return True
    else:
        return False

for i in range(len(b)):
    if b[i] >= a[i] and verify(i):
        q.append(i)

ans = 0
succeed = True
while not len(q) == 0:
    i = q.popleft()
    ni = getNext(i)
    pi = getPrev(i)
    #print(i, b)
    d = b[ni] + b[pi]
    if b[i] % d == a[i] % d:
        ans += b[i] // d - (a[i] // d)
        b[i] = a[i]
    else:
        ans += b[i] // d
        b[i] %= d
    if b[i] < a[i]:
        succeed = False
        break
    if verify(ni):
        q.append(ni)
    if verify(pi):
        q.append(pi)

for i in range(len(b)):
    if a[i] != b[i]:
        succeed = False
        break

if succeed:
    print(ans)
else:
    print(-1)
### BUGGY CODE ###

N = int(input())
p = list(map(float, input().split()))

dp = [[0]*(N+1) for i in range(N)]
# iまで見たときに表の枚数がj枚の確率

dp[0][0] = 1 - p[0]
dp[0][1] = p[0]
for i in range(1, N):
    for j in range(N+1):
        dp[i][j] = dp[i-1][j]*(1-p[i])
        if j > 0:
            dp[i][j] += dp[i-1][j-1]*p[i]

ans = sum(dp[-1][N//2 + 1:])

print(ans)


### FIXED CODE ###

def main():
    N = int(input())
    p = tuple(map(float, input().split()))

    dp = [0 for i in range(N+1)]
    # iまで見たときに表の枚数がj枚の確率

    dp[0] = 1 - p[0]
    dp[1] = p[0]
    for i in range(1, N):
        for j in range(i+1, -1, -1):

            dp[j] = dp[j]*(1-p[i]) + dp[j-1]*p[i]
            # else:
            #     dp[j] = dp[j]*(1-p[i])

    ans = sum(dp[N//2 + 1:])
    print(ans)


main()
### BUGGY CODE ###

N, K, Q = map(int, input().split())
Ai = list(map(int, [input() for i in range(Q)]))

scores = []
for i in range(N):
    scores.append(K)

for j in range(Q):
    scores = list(map(lambda x: x - 1, scores)) 
    scores[Ai[j] - 1] += 1
    scores = scores

for k in range(len(scores)):
    if scores[k] > 0 :
        print('Yes')
    else:
        print('No')

### FIXED CODE ###

N, K, Q = map(int, input().split())
Ai = list(map(int, [input() for i in range(Q)]))

scores = [K-Q for i in range(N)]

for i in range(Q):
    scores[Ai[i] - 1] += 1
    scores = scores


for k in range(len(scores)):
    if scores[k] > 0 :
        print('Yes')
    else:
        print('No')
### BUGGY CODE ###

K, S = map(int, input().split())
ans = 0
for X in range(K+1):
    for Y in range(K+1):
        for Z in range(K+1):
            if X+Y+Z == S:
                ans += 1
print(ans)

### FIXED CODE ###

K, S = map(int, input().split())
ans = 0
for X in range(K+1):
    for Y in range(K+1):
        if K >= S-X-Y >= 0:
            ans += 1
print(ans)
### BUGGY CODE ###

n=int(input())
a=list(map(int,input().split()))
b=list(set(a))
l=[];m=[]
for i in range(len(b)):
  l.append([b[i],a.count(b[i])])
if len(l)>2:
  for j in range(len(b)-2):
    x=l[j][1]
    if l[j+1][0]-l[j][0]<=2:
      x+=l[j+1][1]
      if l[j+2][0]-l[j][0]<=2:x+=l[j+2][1]
    m.append(x)
elif len(l)>1:
  for j in range(len(b)-1):
    x=l[j][1]
    if l[j+1][0]-l[j][0]<=2:x+=l[j+1][1]
    m.append(x)
else:
  m.append(l[0][1])
print(max(m))

### FIXED CODE ###

n=int(input())
a=list(map(int,input().split()))
l=[]
for i in range(max(a)+3):
  l.append(0)
for j in range(n):
  l[a[j]+1]+=1
m=[]
for i in range(1,max(a)+2):
  m.append(l[i-1]+l[i]+l[i+1])
print(max(m))
### BUGGY CODE ###

# N問出題, M回提出
N, M = map(int, input().split())

p_S_list = []

WA = 'WA'
AC = 'AC'

first_AC_index_list = []
AC_set = set([])

for j in range(M):
    p, S = input().split()
    int_p = int(p)
    p_S_list.append([int_p, S])

    if S == AC and (int_p not in AC_set):
        first_AC_index_list.append([j, int_p])
        AC_set.add(int_p)

count_AC = len(first_AC_index_list)
count_WA = 0


for i_list in first_AC_index_list:
    count_WA += p_S_list[:i_list[0]].count([i_list[1], WA])

ans = str(count_AC) + ' ' + str(count_WA)

print(ans)

### FIXED CODE ###

# N問出題, M回提出
N, M = map(int, input().split())

p_S_list = []

WA = 'WA'
AC = 'AC'

question_list = [False] * N
WA_count_list = [0] * N

count_AC = 0
count_WA = 0

for i in range(M):
    p, S = input().split()
    int_p = int(p)
    
    if S == WA and question_list[int_p - 1] == False:
        WA_count_list[int_p - 1] += 1

    if S == AC and question_list[int_p - 1] == False:
        count_AC += 1
        count_WA += WA_count_list[int_p - 1]
        question_list[int_p - 1] = True

print(str(count_AC) + ' ' + str(count_WA))








'''
first_AC_index_list = []
AC_set = set([])

for j in range(M):
    p, S = input().split()
    int_p = int(p)
    p_S_list.append([int_p, S])

    if S == AC and (int_p not in AC_set):
        first_AC_index_list.append([j, int_p])
        AC_set.add(int_p)

count_AC = len(first_AC_index_list)
count_WA = 0
# for i in range(1, N + 1):
#     # i問目の問題について考える
#     if [i, AC] in p_S_list:
#         count_AC += 1

#         first_AC_index = p_S_list.index([i, AC])

#         count_WA += p_S_list[:first_AC_index].count([i, WA])

for i_list in first_AC_index_list:
    count_WA += p_S_list[:i_list[0]].count([i_list[1], WA])

ans = str(count_AC) + ' ' + str(count_WA)

print(ans)

'''
### BUGGY CODE ###

import re
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
import functools
def v(): return input()
def k(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def X(): return list(input())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 9)
mod = 10**9+7
cnt = 0
ans = 0
inf = float("inf")

n,q=I()
s = v()
a = []
for i in range(q):
    r = l()
    a.append(r)
for i in a:
    b = s[i[0]-1:i[1]]
    print(b.count("AC"))


### FIXED CODE ###

import re
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
import functools
def v(): return input()
def k(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def X(): return list(input())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 9)
mod = 10**9+7
cnt = 0
ans = 0
inf = float("inf")

n,q=I()
s = v()
t = [0]*(n+1)
for i in range(n):
    t[i+1]=t[i]+(1 if s[i:i+2]=="AC" else 0)

ans = []
for i in range(q):
    l,r=I()
    ans.append(t[r-1]-t[l-1])
for i in ans:
    print(i)
### BUGGY CODE ###

n,k=map(int,input().split())
a=list(map(lambda x:(int(x)-1)%k,input().split()))
a_=0
cs_a=[0]
for ai in a:
  a_+=ai
  a_%=k
  cs_a.append(a_)
jouyo=[[]for _ in range(k)]
for i,cs in enumerate(cs_a):
  jouyo[cs].append(i)
import bisect
def func(arg):
  if len(arg)<2:
    return 0
  ret=0
  for i in range(len(arg)):
    idx=bisect.bisect_right(arg,arg[i]+k-1)
    ret+=idx-i-1
  return ret
ans=0
for j in jouyo:
  ans+=func(j)
print(ans)


### FIXED CODE ###

n,k=map(int,input().split())
a=list(map(lambda x:(int(x)-1)%k,input().split()))
a_=0
cs_a=[0]
for ai in a:
  a_+=ai
  a_%=k
  cs_a.append(a_)
ans=0
from collections import defaultdict
d=defaultdict(int)
for i in range(n+1):
  ans+=d[cs_a[i]]
  d[cs_a[i]]+=1
  if i>=k-1:
    d[cs_a[i-k+1]]-=1
print(ans)
### BUGGY CODE ###

#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
for i in range(1, n+1):
    ans = 0
    for x in range(1, 40):
        for y in range(1, 40):
            for z in range(1, 40):
                if x**2 + y**2 + z**2 + x*y + y*z + z*x == i:
                    ans += 1
    print(ans)

### FIXED CODE ###

#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
lst = [0]*(n+1)
for x in range(1, 10**2+1):
    for y in range(1, 10**2+1):
        for z in range(1, 10**2+1):
            if 1 <= x**2 + y**2 + z**2 + x*y + y*z + z*x <= n:
                lst[x**2 + y**2 + z**2 + x*y + y*z + z*x] += 1
for i in range(1, n+1):
    print(lst[i])
### BUGGY CODE ###

from collections import defaultdict

def sol():
    S = input()
    T = input()

    setS = set(S)
    setT = set(T)
    for t in setT:
        if not t in setS:
            print('-1')
            return

    posS = defaultdict(list)

    for i, s in enumerate(S):
        posS[s].append(i)
    for s in enumerate(S):
        posS[s].sort()

    prev = -1
    ans = 0
    N = len(S)
    for t in T:
        for p in posS[t]:
            if p > prev:
                ans += p - prev
                prev = p
                break
        else:
            ans += N - prev
            ans += posS[t][0]
            prev = posS[t][0]

    print(ans)





sol()

### FIXED CODE ###

from collections import defaultdict
from bisect import bisect_right

def sol():
    S = input()
    T = input()

    setS = set(S)
    setT = set(T)
    for t in setT:
        if not t in setS:
            print('-1')
            return

    posS = defaultdict(list)

    for i, s in enumerate(S):
        posS[s].append(i)

    for s in enumerate(S):
        posS[s].sort()

    prev = -1
    ans = 0
    N = len(S)

    for t in T:
        next = bisect_right(posS[t], prev)
        if next >= len(posS[t]):
            ans += N - prev
            ans += posS[t][0]
            prev = posS[t][0]
        else:
            ans += posS[t][next] - prev
            prev = posS[t][next]

    print(ans)

sol()
### BUGGY CODE ###

import math


def eratos(num):
    isPrime = [True] * (num + 1)
    isPrime[0] = isPrime[1] = False
    for i in range(2, int(math.sqrt(num))):
        for j in range(2 * i, num, i):
            isPrime[j] = False
    return isPrime


def isLike(isPrime):
    n = len(isPrime)
    array = [False] * (n - 1)
    for i in range(n - 1):
        if isPrime[i] and isPrime[(i + 1) // 2]:
            array[i] = True
    return array


def solve(l, r, array):
    ans = 0
    for i in range(l, r + 1):
        ans += 1 if array[i] else 0
    return ans


Q = int(input())

isPrime = eratos(10 ** 5 + 1)
array = isLike(isPrime)

for i in range(Q):
    l, r = map(int, input().split())
    print(solve(l, r, array))


### FIXED CODE ###

import math


def eratos(num):
    isPrime = [True] * (num + 1)
    isPrime[0] = isPrime[1] = False
    for i in range(2, int(math.sqrt(num))):
        for j in range(2 * i, num, i):
            isPrime[j] = False
    return isPrime


def isLike(isPrime):
    n = len(isPrime)
    array = [False] * (n - 1)
    for i in range(n - 1):
        if isPrime[i] and isPrime[(i + 1) // 2]:
            array[i] = True
    return array


def cumSum(array):
    n = len(array)
    cum = [0] * (len(array))
    for i in range(1, n):
        cum[i] = cum[i - 1]
        cum[i] += 1 if array[i] else 0

    return cum


def solve(l, r, cum):
    return cum[r] - cum[l - 1]


Q = int(input())

isPrime = eratos(10 ** 5 + 1)
array = isLike(isPrime)
cum = cumSum(array)

for i in range(Q):
    l, r = map(int, input().split())
    print(solve(l, r, cum))
### BUGGY CODE ###

import math

n,d,a = map(int,input().split())
x = [0]*n
h = [0]*n
for i in range(n):
    x[i] , h[i] = map(int, input().split())
    
itv = [[0 for i in range(2)] for j in range(n)]
for i in range(n):
    itv[i][0] = x[i]
    itv[i][1] = h[i]
itv.sort()
ans = 0
    
for i in range(n):
    atk = 0
    if itv[i][1] > 0:
        atk = math.ceil(itv[i][1]/a)
        itv[i][1] = 0
        for j in range(i+1,n):
            if itv[j][0] <= itv[i][0] + (2*d):
                if itv[j][1] > 0:
                    itv[j][1] -= atk * a
            else:
                break
    ans += atk
    
print(ans)

### FIXED CODE ###

import math
import bisect
 
n,d,a = map(int,input().split())
x = [0]*n
h = [0]*n
for i in range(n):
    x[i] , h[i] = map(int, input().split())
    
itv = [[0 for i in range(2)] for j in range(n)]
for i in range(n):
    itv[i][0] = x[i]
    itv[i][1] = h[i]
itv.sort()
ans = 0

x.sort()
x.append(1145141919810)
h.append(0)

imos = [0]*(n+1)

atk = math.ceil(itv[0][1]/a)
imos[0] += atk * a
b = bisect.bisect(x,itv[0][0] + (2*d))
imos[b] -= atk * a
ans += atk
    
for i in range(1,n):
    atk = 0
    imos[i] += imos[i-1]
    if itv[i][1] > imos[i]:
        atk = math.ceil((itv[i][1]-imos[i])/a)
        imos[i] += atk * a
        b = bisect.bisect(x,itv[i][0] + (2*d))
        imos[b] -= atk * a
    ans += atk

print(ans)
### BUGGY CODE ###

n,a,b=map(int,input().split())

p = 10 ** 9 + 7

def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用

for i in range(2, n + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

ans=pow(2,n)%p-1-cmb(n,a,p)-cmb(n,b,p)

print(ans%p)


### FIXED CODE ###

n,a,b=map(int,input().split())
c=max(a,b)
b=min(a,b)
a=c
MOD = pow(10,9) + 7

X=1
Y=1

for i in range(1,a+1):
    X=X*(n+1-i)%MOD
    Y=Y*i%MOD
    if i==b:
        b_X=X
        b_Y=Y
a_X=X
a_Y=Y
def calc(X,Y,MOD):
    return X*pow(Y,MOD-2,MOD)

ans=pow(2,n,MOD)%MOD-1-calc(a_X,a_Y,MOD)-calc(b_X,b_Y,MOD)

print(ans%MOD)
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10**9)
N = input()
S = input().strip()
type = len(set(S))

def DP(i,s):
  # 葉チェック
  if i >= len(S):
    return 1 if len(s) > 0 else 0
  if len(s) >= type:
    return 1
  
  # S[i]を採用しない枝
  notadopt = DP(i+1, s)
  
  # S[i]を採用する枝
  if S[i] not in s:
    s += S[i]
    adopt = DP(i+1, s)
  else:
    adopt = 0

  return adopt + notadopt

print(DP(0, '')%(10**9+7))


### FIXED CODE ###

from collections import Counter
input()
S = input().strip()
c = Counter(S)
ans = 1
for k,v in c.items():
  ans *= (v+1)
print((ans-1)%(10**9+7))
### BUGGY CODE ###

from collections import deque
import sys
input = sys.stdin.readline
h, w = map(int, input().split())
grid = []
graph = [[2000 for i in range(w)] for j in range(h)]
#x,y渡すと、（ｈ、ｗ）に入ってるかどうか判定
def check(s,t):
    if (0 <=  s <= h - 1) and (0 <= t <= w - 1):
        return True
    else:
        return False

#graph => そこまでの距離を保存した二次元配列　grid=>与えられた迷路
def bfs(que):
    finished = set()
    while que:
        x , y, cost = que.popleft()
        if (grid[y][x] == '#' and cost != 0):
            continue
        if (x,y) not in finished and graph[y][x] > cost:
            finished.add((x,y))
            graph[y][x] = cost
            if check(y,x+1):
                que.append([x+1,y,cost+1])
            if check(y+1,x):
                que.append([x, y+1, cost+1])
            if check(y,x-1):
                que.append([x-1,y,cost+1])
            if check(y-1,x):
                que.append([x,y-1,cost+1])
for i in range(h):
    grid.append(list(input()))
que = deque()
for i in range(h):
    for j in range(w):
        if grid[i][j] == "#":
            que.append((j,i,0))
bfs(que)
ans = 0
for i in range(h):
    ans = max(ans, max(graph[i]))
print(ans)

### FIXED CODE ###

from collections import deque
import sys
input = sys.stdin.readline
h, w = map(int, input().split())
grid = []
graph = [[2000 for i in range(w)] for j in range(h)]
#x,y渡すと、（ｈ、ｗ）に入ってるかどうか判定
def check(s,t):
    if (0 <=  s <= h - 1) and (0 <= t <= w - 1):
        return True
    else:
        return False

#graph => そこまでの距離を保存した二次元配列　grid=>与えられた迷路
def bfs(que):
    finished = set()
    while que:
        x ,y = que.popleft()
        if y*w+x not in finished:
            finished.add(y*w+x)
            for n_x,n_y in [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]:
                if check(n_y,n_x) and graph[n_y][n_x] > graph[y][x] + 1:
                    graph[n_y][n_x] = graph[y][x] + 1
                    que.append((n_x,n_y))
for i in range(h):
    grid.append(list(input()))
que = deque()
for i in range(h):
    for j in range(w):
        if grid[i][j] == "#":
            graph[i][j] = 0
            que.append((j,i))
bfs(que)
ans = 0
for i in range(h):
    ans = max(ans, max(graph[i]))
print(ans)
### BUGGY CODE ###

import collections

N = int(input())
stuff = list(map(int, input().split()))

stuff_lis = collections.Counter(stuff)
st = list(stuff_lis.keys())
num = list(stuff_lis.values())
num_d = collections.deque(num)

for i in range(N):
    if i+1 in st:
        print(num_d.popleft())
    else:
        print(0)


### FIXED CODE ###

N = int(input())
A = list(input().split())
A = [int(A[i]) for i in range(N-1)]
ans = [0 for i in range(N)]

for i in range(N-1):
    ans[A[i] - 1] += 1

for i in range(N):
    print(ans[i])
### BUGGY CODE ###

#!/usr/bin/env python3
import sys

def calc(order, groups, D):
    ret = 0
    for i, G in enumerate(groups):
        target = order[i]
        for elm in G:
            #print(elm, target)
            ret += D[elm - 1][target]
    return ret

def dfs(idx, current, used, groups, D):
    if idx == 3:
        ret = calc(current, groups, D)
        return ret
    ret = float('inf')
    for i, u in enumerate(used):
        if not u:
            used[i] = True
            tmp = dfs(idx + 1, current + [i], used, groups, D)
            ret = min(ret, tmp)
            used[i] = False
    return ret

def solve(N: int, C: int, D: "List[List[int]]", c: "List[List[int]]"):
    groups = [[] for _ in range(3)]
    for i in range(N):
        for j in range(N):
            cc = c[i][j]
            groups[(i + j) % 3].append(cc)
    #print(groups)
    ret = dfs(0, [], [False] * C, groups, D)
    print(ret)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    D = [ [ int(next(tokens)) for _ in range(C) ] for _ in range(C) ]  # type: "List[List[int]]"
    c = [ [ int(next(tokens)) for _ in range(N) ] for _ in range(N) ]  # type: "List[List[int]]"
    solve(N, C, D, c)

if __name__ == '__main__':
    main()


### FIXED CODE ###

#!/usr/bin/env python3
import sys

def calc_(order, d):
    ret = 0
    for i in range(3):
        target = order[i]
        ret += d[i][target]
    return ret

def calc(G, target, D):
    ret = 0
    for elm in G:
        ret += D[elm - 1][target]
    return ret

def dfs(idx, current, used, d):
    if idx == 3:
        ret = calc_(current, d)
        return ret
    ret = float('inf')
    for i, u in enumerate(used):
        if not u:
            used[i] = True
            tmp = dfs(idx + 1, current + [i], used, d)
            ret = min(ret, tmp)
            used[i] = False
    return ret

def solve(N: int, C: int, D: "List[List[int]]", c: "List[List[int]]"):
    groups = [[] for _ in range(3)]
    for i in range(N):
        for j in range(N):
            cc = c[i][j]
            groups[(i + j) % 3].append(cc)
    #print(groups)
    d = [[] for _ in range(3)]
    for i, G in enumerate(groups):
        for j in range(C):
            d[i].append(calc(G, j, D))
    ret = dfs(0, [], [False] * C, d)
    print(ret)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    D = [ [ int(next(tokens)) for _ in range(C) ] for _ in range(C) ]  # type: "List[List[int]]"
    c = [ [ int(next(tokens)) for _ in range(N) ] for _ in range(N) ]  # type: "List[List[int]]"
    solve(N, C, D, c)

if __name__ == '__main__':
    main()
### BUGGY CODE ###

import sys
import heapq
import bisect
 
mod = 10**9+7
 
def I(): return(int(sys.stdin.readline()))
def LI(): return([int(x) for x in sys.stdin.readline().split()])
def S(): return(list(sys.stdin.readline())[:-1])
 
def main():
    H,W = LI()
    A = [LI() for _ in range(H)]
    B = [LI() for _ in range(H)]
    D = [[A[h][w]-B[h][w] for w in range(W)] for h in range(H)]
    dp = [[[False for _ in range(26000)] for w in range(W)] for h in range(H)]

    dp[0][0][D[0][0]+13000] = True

    for h in range(H):
        for w in range(W):
            if(h>0):
                for i in range(26000):
                    if dp[h-1][w][i]:
                        dp[h][w][i+D[h][w]] = True
                        dp[h][w][i-D[h][w]] = True
            if(w>0):
                for i in range(26000):
                    if dp[h][w-1][i]:
                        dp[h][w][i+D[h][w]] = True
                        dp[h][w][i-D[h][w]] = True

    ans = 30000
    for i in range(26000):
        if dp[H-1][W-1][i]:
            ans = min(ans,abs(i-13000))
    return(ans)
 
if __name__ == "__main__":
    print(main())


### FIXED 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=[[0]*W for _ in range(H)]
    dp[0][0]=1<<D[0][0]<<20000

    for h in range(H):
        for w in range(W):
            if(h>0):
                dp[h][w] |= dp[h-1][w]<<D[h][w]
                dp[h][w] |= dp[h-1][w]>>D[h][w]
            if(w>0):
                dp[h][w] |= dp[h][w-1]<<D[h][w]
                dp[h][w] |= dp[h][w-1]>>D[h][w]
    for i in range(81):
        bit = 1<<(20000+i)
        bit |= 1<<(20000-i)
        if dp[H-1][W-1]&bit:
            return(i)
 
if __name__ == "__main__":
    print(main())