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

N, K = map(int, input().split())
if N % K == 0:
    print(0)
else:
    li = []
    li.append(N)
    aoki = N
    while aoki <= min(li):
        aoki = abs(min(li) - K)
        li.append(aoki)
    print(min(li))


### FIXED CODE ###

n, k = map(int, input().split())
if n==0 or k==1:
    print(0)
    exit()
elif n<k:
    print(min(n, abs(n-k)))
    exit()
elif n % k == 0:
    print(0)
    exit()
else:
    mx = n%k
print(min(abs(mx-k), mx))
### BUGGY CODE ###

import math
from itertools import product
from collections import deque

h, w = map(int, input().split())
ch, cw = map(lambda x: int(x) - 1, input().split())
dh, dw = map(lambda x: int(x) - 1, input().split())
S = [input() for _ in range(h)]


distance = [[math.inf for _ in range(w)] for _ in range(h)]
distance[ch][cw] = 0
queue = deque([(ch, cw)])
pathes = {(0, -1), (-1, 0), (0, 1), (1, 0)}
warps = set(product(range(-2, 3), range(-2, 3))) - {(0, 0)} - pathes

while queue:
    i, j = queue.popleft()
    for pi, pj in pathes:
        u, v = i+pi, j+pj
        if 0 <= u < h and 0 <= v < w and S[u][v] == '.' and distance[u][v] > distance[i][j]:
            distance[u][v] = distance[i][j]
            queue.appendleft((u, v))

    for wi, wj in warps:
        x, y = i + wi, j + wj
        if 0 <= x < h and 0 <= y < w and S[x][y] == '.' and distance[x][y] > distance[i][j] + 1:
            distance[x][y] = distance[i][j] + 1
            queue.append((x, y))

print(distance[dh][dw] if distance[dh][dw] != math.inf else -1)


### FIXED CODE ###

import math
from itertools import product
from collections import deque

h, w = map(int, input().split())
ch, cw = map(lambda x: int(x) - 1, input().split())
dh, dw = map(lambda x: int(x) - 1, input().split())
S = [input() for _ in range(h)]


distance = [[math.inf for _ in range(w)] for _ in range(h)]
distance[ch][cw] = 0
queue = deque([(ch, cw)])
pathes = {(0, -1), (-1, 0), (0, 1), (1, 0)}
warps = set(product(range(-2, 3), range(-2, 3))) - {(0, 0)} - pathes

while queue:
    i, j = queue.popleft()
    for pi, pj in pathes:
        u, v = i+pi, j+pj
        if 0 <= u < h and 0 <= v < w and S[u][v] == '.' and distance[u][v] > distance[i][j]:
            distance[u][v] = distance[i][j]
            queue.appendleft((u, v))

    for wi, wj in warps:
        x, y = i + wi, j + wj
        if 0 <= x < h and 0 <= y < w and S[x][y] == '.' and distance[x][y] > distance[i][j] + 1:
            distance[x][y] = distance[i][j] + 1
            queue.append((x, y))

print(distance[dh][dw] if distance[dh][dw] != math.inf else -1)
### BUGGY CODE ###

n=int(input())
arr=list(map(int,input().split()))
arr=sorted(arr,reverse=True)
dic={}
for val in arr:
  if val not in dic:
    dic[val]=1
  else:
    dic[val]+=1
ans=0
for val in arr:
  for i in range(40):
    if val<2**i:
      persuit=2**i
      break
  if persuit-val==val:
    if val in dic:
      if dic[val]>=2:
        ans+=1
        dic[val]-=2
        if dic[val]==0:
          del dic[val]
      else:
        continue
    else:
      continue
  else:
    if val in dic and persuit-val in dic:
      ans+=1
      dic[val]-=1
      if dic[val]==0:
        del dic[val]
      dic[persuit-val]-=1
      if dic[persuit-val]==0:
        del dic[persuit-val]
    else:
      continue
print(ans)

### FIXED CODE ###

n=int(input())
arr=list(map(int,input().split()))
arr=sorted(arr,reverse=True)
dic={}
for val in arr:
  if val not in dic:
    dic[val]=1
  else:
    dic[val]+=1
ans=0
for val in arr:
  for i in range(40):
    if val<2**i:
      persuit=2**i
      break
  if persuit-val==val:
    if val in dic:
      if dic[val]>=2:
        ans+=1
        dic[val]-=2
        if dic[val]==0:
          del dic[val]
      else:
        continue
    else:
      continue
  else:
    if val in dic and persuit-val in dic:
      ans+=1
      dic[val]-=1
      if dic[val]==0:
        del dic[val]
      dic[persuit-val]-=1
      if dic[persuit-val]==0:
        del dic[persuit-val]
    else:
      continue
print(ans)
### BUGGY CODE ###

import bisect
import heapq
n, m = map(int, input().split())
#a = sorted(list(map(int, input().split())))
a = list(map(int, input().split()))
#a = list(map(lambda x: x * -1, a))
b, c = [], []
heapq.heapify(a)

for i in range(m):
    v1, v2 = map(int, input().split())
    b.append(v1)
    c.append(v2)

for i in range(m):
    cnt = 0
    while True:
        if cnt == b[i]:
            break
        #minV = -heapq.heappop(a)
        minV = heapq.heappop(a)
        #print('# minV: ' + str(minV))
        if minV >= c[i]:
            heapq.heappush(a, minV)
            break
        else:
            heapq.heappush(a, c[i])
        cnt += 1

#print(a)
print(sum(a))




### FIXED CODE ###

import bisect
import heapq
n, m = map(int, input().split())
a = list(map(int, input().split()))
#b, c = [], []
bc = []
heapq.heapify(a)

for i in range(m):
    bc.append(list(map(int, input().split())))
    # v1, v2 = map(int, input().split())
    # b.append(v1)
    # c.append(v2)
bc.sort(key = lambda x: x[1], reverse=True)

for i in range(m):
    cnt = 0
    while True:
        if cnt == bc[i][0]:
            break
        minV = heapq.heappop(a)
        #print('# minV: ' + str(minV))
        if minV >= bc[i][1]:
            heapq.heappush(a, minV)
            break
        else:
            heapq.heappush(a, bc[i][1])
        cnt += 1

#print(a)
print(sum(a))
### BUGGY CODE ###

import heapq
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
h = [[-B[i],i] for i in range(N) if B[i] != A[i]]
heapq.heapify(h)

ans = 0
while h:
    b,i = heapq.heappop(h)
    b *= -1
    a = B[(i-1)%N]
    c = B[(i+1)%N]
    if a+c > b or b != B[i]:
        continue
    if b < A[i]:
        ans = -1
        break
    if (b-A[i])%(a+c)==0:
        ans += (b-A[i])//(a+c)
        B[i] = A[i]
    else:
        ans += b//(a+c)
        b %= a+c
        B[i] = b
        heapq.heappush(h,[-b,i])
        if a != A[(i-1)%N]:
            heapq.heappush(h,[-a,(i-1)%N])
        if c != A[(i+1)%N]:
            heapq.heappush(h,[-c,(i+1)%N])
if A != B:
    ans = -1
print(ans)

### FIXED CODE ###

N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))


ans = 0
f = True
while f:
    f = False
    for i in range(N):
        a,b,c = B[(i-1)%N],B[i],B[(i+1)%N]
        if b > a+c and b > A[i]:
            if (b-A[i])%(a+c)==0:
                B[i] = A[i]
                ans += (b-A[i])//(a+c)
            else:
                ans += B[i]//(a+c)
                B[i] %= a+c
            f = True

if A != B:
    ans = -1
print(ans)
### BUGGY CODE ###

import sys
input = sys.stdin.readline

R, C, K = map(int, input().split())
D = dict()
for _ in range(K):
    r, c, v = map(int, input().split())
    D[(r, c)] = v

dp = [[[0] * 4 for _ in range(C + 1)] for _ in range(R + 1)]
for r in range(1, R + 1):
    for c in range(1, C + 1):
        m=max(dp[r-1][c])
        for n in range(4):
            dp[r][c][n] = max(m,
                              dp[r][c - 1][n])
        if (r, c) in D:
            for n in range(3):
                dp[r][c][n + 1] = max(dp[r][c][n + 1],
                                      m + D[(r, c)],
                                      dp[r][c - 1][n] + D[(r, c)])
print(max(dp[-1][-1]))


### FIXED CODE ###

import sys

input = sys.stdin.readline

R, C, K = map(int, input().split())
D = dict()
for _ in range(K):
    r, c, v = map(int, input().split())
    D[(r, c)] = v

dp0 = [[0] * (C + 1) for _ in range(R + 1)]
dp1 = [[0] * (C + 1) for _ in range(R + 1)]
dp2 = [[0] * (C + 1) for _ in range(R + 1)]
dp3 = [[0] * (C + 1) for _ in range(R + 1)]

for r in range(1, R + 1):
    for c in range(1, C + 1):
        m = max(dp0[r - 1][c], dp1[r - 1][c], dp2[r - 1][c], dp3[r - 1][c])
        dp0[r][c] = max(m, dp0[r][c - 1])
        dp1[r][c] = max(m, dp1[r][c - 1])
        dp2[r][c] = max(m, dp2[r][c - 1])
        dp3[r][c] = max(m, dp3[r][c - 1])
        if (r, c) in D:
            dp1[r][c] = max(dp1[r][c], m + D[(r, c)], dp0[r][c - 1] + D[(r, c)])
            dp2[r][c] = max(dp2[r][c], m + D[(r, c)], dp1[r][c - 1] + D[(r, c)])
            dp3[r][c] = max(dp3[r][c], m + D[(r, c)], dp2[r][c - 1] + D[(r, c)])
print(max(dp0[-1][-1], dp1[-1][-1], dp2[-1][-1], dp3[-1][-1]))
### BUGGY CODE ###

import sys

while 1:
    n = int(input())
    if n == 0:
        break
    a = [int(input()) for _ in range(n)]
    sumMax = 0

    for i in range(len(a)+1):
        for j in range(i, len(a)+1):
            if sum(a[i:j]) > sumMax:
                sumMax = sum(a[i:j])

    print(sumMax)

### FIXED CODE ###

while 1:
    n = int(input())
    if n == 0:
        break
    a = []
    for _ in range(n):
        a.append(int(input()))

    dp = []
    dp.append(a[0])
    for i in range(1,len(a)):
        dp.append(max(dp[i-1] + a[i], a[i]))

    print(max(dp))
### BUGGY CODE ###

import sys

n, k = map(int, input().split())

if k == 1:
    print(0)
    sys.exit()

# x = n
while True:
    min_n = n
    n = abs(n-k)
    if min_n >= n:
        min_n = n
    else:
        break
print(min_n)


### FIXED CODE ###

import sys
import math

n, k = map(int, input().split())

# n_start = math.floor(n / k)
# # print(n_start)
# n = n - n_start*k
# # print(n)

n = n % k

while True:
    min_n = n
    n = abs(n-k)
    # print("n, k =", n, k)
    if min_n > n:
        min_n = n
    else:
        break
print(min_n)
### BUGGY CODE ###

n = int(input())

# 最初の得票は、最小値を目指すので
# 単純に入力比をそのまま使用
vote = [int(i) for i in input().split()]

# 各入力に対し、vote[0]<tk, vote[1]<akとなる
# 最小のtk,akでvoteを更新
for i in range(n-1):
    # print(i)
    t, a = [int(i) for i in input().split()]
    # vote[0]<tk, vote[1]<akとなるkを算出(k<nなのでO(n))
    for k in range(1, 10000000):
        # print("k:{}".format(k))
        if t*k >= vote[0] and a*k >= vote[1]:
            vote = [t*k, a*k]
            break
    # print("vote:{}".format(vote))
print(sum(vote))

### FIXED CODE ###

import math

n = int(input())
vote = [0, 0]
# 最初の得票は、最小値を目指すので
# 単純に入力比をそのまま使用
# 各入力に対し、vote[0]<=t*k, vote[1]<=a*kとなる
# 最小のt*k,a*kでvoteを更新
vote = [1, 1]
for i in range(n):
    t, a = [int(i) for i in input().split()]
    if vote[0] % t == 0:
        k = vote[0] // t
    else:
        k = vote[0] // t + 1
    if vote[1] % a == 0:
        k = max(k, vote[1] // a)
    else:
        k = max(k, vote[1] // a + 1)
    # k = max(math.ceil(vote[0] / t), math.ceil(vote[1] / a))
    vote = [t * k, a * k]
    # a / b + (a % b == 0 ? 0: 1)
    # print("i:{} vote:{}".format(i, vote))
print(vote[0] + vote[1])
### BUGGY CODE ###

#!/usr/bin/env python3

import sys
sys.setrecursionlimit(10 ** 6)

def main():
    n = int(input())
    adj_list = [[] for i in range(n)]
    for i in range(n - 1):
        a1, b1 = map(int, sys.stdin.readline().split())
        adj_list[a1 - 1].append(b1 - 1)
        adj_list[b1 - 1].append(a1 - 1)
    path = dfs(0, -1, adj_list, n)
    assert len(path) >= 2
    fpath = len(path) - len(path) // 2
    cut = set(path[fpath - 1:fpath + 1])
    f = dfs2(0, -1, adj_list, n, cut)
    s = dfs2(n - 1, -1, adj_list, n, cut)
    assert f + s == n
    print("Fennec" if f > s else "Snuke")

def dfs(now, prev, adj_list, n):
    if now == n - 1:
        return [now]
    for next in adj_list[now]:
        if next == prev:
            continue
        p = dfs(next, now, adj_list, n)
        if p is not None:
            return [now] + p

def dfs2(now, prev, adj_list, n, cut):
    size = 1
    for next in adj_list[now]:
        if next == prev:
            continue
        if {now, next} == cut:
            continue
        s = dfs2(next, now, adj_list, n, cut)
        size += s
    return size

if __name__ == "__main__":
    main()


### FIXED CODE ###

#!/usr/bin/env python3

import sys
sys.setrecursionlimit(10 ** 6)

def main():
    n = int(input())
    adj_list = [[] for i in range(n)]
    for i in range(n - 1):
        a1, b1 = map(int, sys.stdin.readline().split())
        adj_list[a1 - 1].append(b1 - 1)
        adj_list[b1 - 1].append(a1 - 1)
    path = list(reversed(dfs(0, -1, adj_list, n)))
    assert len(path) >= 2
    fpath = len(path) - len(path) // 2
    cut = set(path[fpath - 1:fpath + 1])
    f = dfs2(0, -1, adj_list, n, cut)
    s = dfs2(n - 1, -1, adj_list, n, cut)
    assert f + s == n
    print("Fennec" if f > s else "Snuke")

def dfs(now, prev, adj_list, n):
    if now == n - 1:
        return [now]
    for next in adj_list[now]:
        if next == prev:
            continue
        p = dfs(next, now, adj_list, n)
        if p is not None:
            p.append(now)
            return p

def dfs2(now, prev, adj_list, n, cut):
    size = 1
    for next in adj_list[now]:
        if next == prev:
            continue
        if {now, next} == cut:
            continue
        s = dfs2(next, now, adj_list, n, cut)
        size += s
    return size

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

def main():

    n, m = map(int, input().split())
    a = [int(input()) for i in range(m)]
    mod = 1000000007

    # フィボナッチ数列を作る要領で行う
    d = [0] * (n+1)
    # 2回0が続く状況aに連番があったら即座に終了する
    cnt = 0 
    # d[0]とd[1]を規定。aに1が含まれていることを考慮して場合分けしておく
    d[0] = 1
    if 1 not in a:
        d[1] = 1
    # else:
    #     d[1] = 1
    # 階段番号は2~nまでを見る必要がある
    for i in range(2, n+1):
        if i in a:
            d[i] = 0
            cnt += 1
            if cnt == 2:
                print('0')
                exit()
        else:
            d[i] = d[i-1] + d[i-2]
            cnt = 0
    # print(d)  
    ans = d[n] % mod        
    print(ans)

if __name__ == '__main__':
    main()

### FIXED CODE ###

import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

def main():
    # n, m = map(int, input().split())
    # a = [int(input()) for i in range(m)]
    n, m = map(int, readline().split())
    a = set(map(int, read().split()))
    mod = 1000000007

    # フィボナッチ数列を作る要領で行う
    d = [0] * (n+1)
    # 2回0が続く状況aに連番があったら即座に終了する
    cnt = 0 
    # d[0]とd[1]を規定。aに1が含まれていることを考慮して場合分けしておく
    d[0] = 1
    if 1 not in a:
        d[1] = 1
    # else:
    #     d[1] = 1
    # 階段番号は2~nまでを見る必要がある
    for i in range(2, n+1):
        if i in a:
            d[i] = 0
            cnt += 1
            if cnt == 2:
                print('0')
                exit()
        else:
            d[i] = (d[i-1] + d[i-2]) % mod
            cnt = 0
    # print(d)  
    ans = d[n]        
    print(ans)

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

s=input()
n=len(s)
a=0
b=1
M=10**9+7
p=[1]
for _ in range(n):
  p.append(p[-1]*3%M)
for i,t in enumerate(s):
  if int(t):
    a=(a+b*p[n-i-1])%M
    b*=2
print((a+b)%M)

### FIXED CODE ###

def main():
  s=input()
  n=len(s)
  a,b,M=0,1,10**9+7
  p=[1]
  for i in range(n-1):
    p.append(p[i]*3%M)
  for i,t in enumerate(map(int,s)):
    if t:
      a=(a+b*p[~i])%M
      b=b*2%M
  print((a+b)%M)
main()
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10000000)

N,Q=map(int,input().split())

T=[[] for i in range(N)]

for i in range(N-1):
    a,b=map(int,input().split())
    T[a-1].append(b-1)
    T[b-1].append(a-1)

O=[0 for i in range(N)]

for i in range(Q):
    p,x=map(int,input().split())
    O[p-1]+=x

def dfs(n):
    for i in T[n]:
        if r[i]==1:continue
        r[i]=1
        O[i]+=O[n]
        dfs(i)

r=[1]+[0]*(N-1)

dfs(0)

print(*O)
    


### FIXED CODE ###

import sys
sys.setrecursionlimit(10000000)
input=sys.stdin.readline

N,Q=map(int,input().split())

T=[[] for i in range(N)]

for i in range(N-1):
    a,b=map(int,input().split())
    T[a-1].append(b-1)
    T[b-1].append(a-1)

O=[0 for i in range(N)]

for i in range(Q):
    p,x=map(int,input().split())
    O[p-1]+=x

def dfs(n):
    for i in T[n]:
        if r[i]:continue
        r[i]=1
        O[i]+=O[n]
        dfs(i)

r=[1]+[0]*(N-1)

dfs(0)

print(*O)
### BUGGY CODE ###

import sys, heapq, copy
from collections import deque
input = sys.stdin.readline
'''
allinputs = iter(input().splitlines())
input = lambda : next(allinputs)
#'''

N, K = map(int, input().split())
V_init = deque(map(int, input().split()))
max_score = 0
hands = [0] * K
heapq.heapify(hands)

for i_rget in range(K + 1):
	for i_lget in range(max(K - i_rget, 0) + 1):
		for i_del in range(max(K - i_rget - i_lget, 0) + 1):
			score = 0
			hands = [0] * K
			V = copy.copy(V_init)
			for i in range(i_rget + 1):
				if i > 0 and V:
					tmp = V.pop()					
					heapq.heappush(hands, tmp)
					score += tmp
				
			for i in range(i_lget + 1):
				if i > 0 and V:
					tmp = V.popleft()
					heapq.heappush(hands, tmp)
					score += tmp
			
			for i in range(i_del + 1):
				if i > 0:
					tmp = heapq.heappop(hands)
					score -= tmp
			
			if score > max_score:
				max_score = score

print(max_score)


### FIXED CODE ###

import sys, heapq, copy
from collections import deque
input = sys.stdin.readline
'''
allinputs = iter(input().splitlines())
input = lambda : next(allinputs)
#'''

N, K = map(int, input().split())
V_init = deque(map(int, input().split()))
max_score = 0
hands = [0] * K
heapq.heapify(hands)

for i_rget in range(K + 1):
	for i_lget in range(max(K - i_rget, 0) + 1):
		tmp = 0
		score = 0
		hands = [0] * K
		V = copy.copy(V_init)
		for i in range(i_rget + 1):
			if i > 0 and V:
				tmp = V.pop()					
				heapq.heappush(hands, tmp)
				score += tmp
			
		for i in range(i_lget + 1):
			if i > 0 and V:
				tmp = V.popleft()
				heapq.heappush(hands, tmp)
				score += tmp
		
		for i in range(max(K - i_rget - i_lget, 0) + 1):
			if i > 0:
				tmp = heapq.heappop(hands)
				if tmp < 0:
					score -= tmp
				else:
					break
		
		if score > max_score:
			max_score = score

print(max_score)
### BUGGY CODE ###

import sys
input = sys.stdin.readline

X,Y,Z,K=map(int,input().split())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
C=list(map(int,input().split()))

AB=[]
for a in A:
    for b in B:
        AB.append(a+b)

AB.sort(reverse=True)
AB=AB[:K]

ALL=[]

for ab in AB:
    for c in C:
        ALL.append(ab+c)

ALL.sort(reverse=True)

for k in range(K):
    print(ALL[k])


### FIXED CODE ###

import sys
input = sys.stdin.readline

X,Y,Z,K=map(int,input().split())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
C=list(map(int,input().split()))

AB=[]
for a in A:
    for b in B:
        AB.append(a+b)

AB.sort(reverse=True)
AB=AB[:K]

ALL=[]

for ab in AB:
    for c in C:
        ALL.append(ab+c)

ALL.sort(reverse=True)

for k in range(K):
    print(ALL[k])
### BUGGY CODE ###

#!/usr/bin/env python3

def main():
    N=int(input())
    A = list(map(int, input().split()))
    ans=[]
    for i in range(1,N+1):
        ans.append(str(A.index(i)+1))
    ans = ' '.join(ans)
    print(ans)
    
if __name__ == "__main__":
    main()


### FIXED CODE ###

#!/usr/bin/env python3

def main():
    N=int(input())
    A = list(map(int,input().split()))
    ans=[None]*N
    i=1
    for a in A:
        ans[a-1]=str(i)
        i+=1
    print(' '.join(ans))

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

import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy,copy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def main():
    n, k = MAP()
    p = LIST()

    ans = 0
    tmp = 0

    for i in range(n-k+1):
        if tmp <= sum(p[i:i+k]):
            l = p[i:i+k]
            tmp = sum(p[i:i+k])

    #print(l)
    k = list(accumulate(range(max(l)+1)))

    for x in l:
        ans += k[x]/x
        
    print(ans)

if __name__=='__main__':
    main()


### FIXED CODE ###

import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy,copy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def main():
    n, k = MAP()
    p = LIST()
    ans = 0
    tmp = 0
    if n == k:
        k = list(accumulate(range(max(p)+1)))
        for x in p:
            ans += k[x]/x
        
        print(ans)
        sys.exit()

    p_ = list(accumulate(p))
    #print(p_)


    for i in range(n-k):
        #print(i,p_[i+k]-p_[i])
        if tmp <= p_[i+k]-p_[i]:
            l = p[i+1:i+k+1]
            tmp = p_[i+k]-p_[i]

    #print('l:',l)
    k = list(accumulate(range(max(l)+1)))

    for x in l:
        ans += k[x]/x
        
    print(ans)

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

#ABC089-D
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(input())
def S(): return list(input())
h,w,d=IL()
A=[IL() for i in range(h)]
Al=[0]*(h*w+1)
for i in range(h):
    for j in range(w):
        Al[A[i][j]]=[i,j]

q=I()
for w in range(q):
    ans=0
    l,r=IL()
    for i in range((r-l)//d):
        
        ans+=abs(Al[l+d*i][0]-Al[l+d*(i+1)][0])+abs(Al[l+d*i][1]-Al[l+d*(i+1)][1])
    print(ans)

### FIXED CODE ###

# ABC089-D
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(input())
def S(): return list(input())
h,w,d=IL()
A=[IL() for i in range(h)]
Al=[0]*(h*w+1)
for i in range(h):
    for j in range(w):
        Al[A[i][j]]=[i,j]

rui={}
for i in range(d):
    T=[0]
    for j in range(1,h*w+1-i-d,d):
        T.append(abs(Al[j+i][0]-Al[j+d+i][0])+abs(Al[j+i][1]-Al[j+d+i][1]))
    for j in range(len(T)-1):
        T[j+1]+=T[j]
    rui[(i+1)%d]=T
q=I()
for w in range(q):
    l,r=IL()
    idx=l%d
    if idx==0:
        li=l//d-1
        ri=r//d-1
    else:
        li=l//d
        ri=r//d
    print(rui[idx][ri]-rui[idx][li])
### BUGGY CODE ###

# diverta 2019 Programming Contest: B – RGB Boxes
R, G, B, N = [int(i) for i in input().split()]

bingo = 0

for r in range(N + 1):
    for g in range(N + 1):
        b = (N - (R * r + G * g)) // B
        if b >= 0 and R * r + G * g + B * b == N:
            bingo += 1

print(bingo)

### FIXED CODE ###

# diverta 2019 Programming Contest: B – RGB Boxes
R, G, B, N = [int(i) for i in input().split()]

bingo = 0

for r in range(0, 3001):
    if R * r > N:
        break
    else:
        for g in range(0, 3001):
            b = (N -(R * r + G * g)) // B
            if b < 0:
                break
            elif R * r + G * g + B * b == N:
                bingo += 1

print(bingo)