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

import sys
from io import StringIO
import unittest


def resolve():
    N, K = [int(i) for i in input().split()]
    H = sorted([int(i) for i in input().split()])
    H.reverse()
    for i in range(K):
        if len(H) > 0:
            H.remove(H[0])
        else:
            break
    sumH = 0
    if len(H) > 0:
        sumH = sum(H)
    print(sumH)


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """3 1
4 1 5"""
        output = """5"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """8 9
7 9 3 2 3 8 4 6"""
        output = """0"""
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = """3 0
1000000000 1000000000 1000000000"""
        output = """3000000000"""
        self.assertIO(input, output)


if __name__ == "__main__":
    # unittest.main()
    resolve()


### FIXED CODE ###

import sys
from io import StringIO
import unittest


def resolve():
    N, K = [int(i) for i in input().split()]
    H = sorted([int(i) for i in input().split()])
    if N <= K:
        H = [0]
    else:
        # if K < (N - K):
        for i in range(K):
            H[len(H) - 1 - i] = 0
        # else:
        #     Hs = []
        #     for i in range(N - K):
        #         Hs.append(H[i])
        #     H = Hs
    print(sum(H))


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """3 1
4 1 5"""
        output = """5"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """8 9
7 9 3 2 3 8 4 6"""
        output = """0"""
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = """3 0
1000000000 1000000000 1000000000"""
        output = """3000000000"""
        self.assertIO(input, output)


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

def insert(S, string):
    S.append(string)

def find(S, string):
    cnt = 0
    for i in range(len(S)):
        cnt = cnt + 1
        if S[i] == string:
            print 'yes'
            break
        elif cnt == len(S):
            print 'no'

    if cnt == 0:
        print 'no'

n = input()

S = []

for i in range(n):
    tmp1, tmp2  = map(str,raw_input().split())
    if tmp1 == 'insert':
        insert(S, tmp2)
    elif tmp1 == 'find':
        find(S, tmp2)
    else:
        print 'error!'

### FIXED CODE ###

def insert(S, string):
    S.add(string)

def find(S, string):
    if string in S:
        print 'yes'
    else:
        print 'no'

n = input()

S = set()

for i in range(n):
    tmp1, tmp2  = map(str, raw_input().split())
    if tmp1 == 'insert':
        insert(S, tmp2)
    elif tmp1 == 'find':
        find(S, tmp2)
    else:
        print 'error!'
### BUGGY CODE ###

from math import factorial 

N,a,b=map(int,input().split())
mod=10**9+7


def rapid_comb(N,K):
    bunsi=bunbo=1
    for i in range(K):
        bunsi*=(N-i)%mod
        bunbo*=(i+1)%mod
    return bunsi*pow(bunbo,mod-2,mod)

ans=((pow(2,N,mod)-1)%mod-rapid_comb(N,a)-rapid_comb(N,b))%mod

#逆元の割り算のmodは、分子*逆元（分母)%modと等価　フェルマーの小定理から、 逆元はpow(b,mod-2,mod)となる

print(ans)

### FIXED CODE ###

N,a,b=map(int,input().split())
mod=10**9+7

def cmb(N,K):
    r=1

    for i in range(K):
        r=r*(N-i)*pow(i+1,mod-2,mod)%mod

    return r
ans=((pow(2,N,mod)-1)%mod-cmb(N,a)-cmb(N,b))%mod
#逆元の割り算のmodは、分子*逆元（分母)%modと等価　フェルマーの小定理から、 逆元はpow(b,mod-2,mod)となる
print(ans)
### BUGGY CODE ###

n = int(input())
an = [int(i) for i in input().split()]
order = []
for i in range(n):
    index = an.index(i + 1)
    order.append(index + 1)

for i in range(n - 1):
    print(str(order[i]), end=' ')
print(order[n - 1])

### FIXED CODE ###

n = int(input())
a = [int(i) for i in input().split()]
order = [0 for i in range(n)]
for i in range(n):
    order[a[i] - 1] = i + 1
for i in range(n - 1):
    print(str(order[i]), end=' ')
print(order[n - 1])
### BUGGY CODE ###

print(sum(range(int(input()))))


### FIXED CODE ###

n = int(input())
print(n*(n-1)//2)
### BUGGY CODE ###

n,m,k = map(int,input().split())
A = [int(p) for p in input().split()]
B = [int(p) for p in input().split()]
a,b = [0],[0]

a_apnd = a.append
b_apnd = b.append
for i in range(n):
  a_apnd(a[i]+A[i])
for i in range(m):
  b_apnd(b[i]+B[i])
  
b_apnd((10**9)+1)
count = 0
for i in range(n+1):
  res = k-a[i]
  if res<0:
    break
  for t in range(m+2):
    if b[t] > res:
      t -= 1
      break
  if count<(i+t):
    count = i+t

print(count)

### FIXED CODE ###

n,m,k = map(int,input().split())
A = [int(p) for p in input().split()]
B = [int(p) for p in input().split()]
a,b = [0],[0]

a_apnd = a.append
b_apnd = b.append
for i in range(n):
  a_apnd(a[i]+A[i])
for i in range(m):
  b_apnd(b[i]+B[i])

count = 0
t = m
for i in range(n+1):
  if k<a[i]:
    break
  while b[t] > k-a[i]:
    t -= 1
  count = max(count,i+t)

print(count)
### BUGGY CODE ###

import sys
import os
import math

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

MOD = 10 ** 9 + 7


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    S = [''.join(sorted(iss())) for _ in range(N)]
    ret = 0
    for s in S:
        ret += S.count(s) - 1
    print(ret // 2)


if __name__ == '__main__':
    main()


### FIXED CODE ###

import sys
import os


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = int(sys.stdin.readline().rstrip())
    lines = ["".join(sorted(line.rstrip())) for line in sys.stdin.readlines()]

    ret = 0
    sortedlines = {}
    for n in range(N):
        item = lines[n]
        if item in sortedlines:
            sortedlines[item] += 1
            ret += sortedlines[item] - 1
        else:
            sortedlines[item] = 1

    print(ret)


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

from collections import deque
import sys


def bfs(x1, y1, d):
    q = deque()
    q.append((d, x1, y1))

    while q:
        d, x1, y1 = q.popleft()

        M[x1][y1] = d

        if [x1, y1] == [xg, yg]:
            print(d)
            return

        for dx, dy in ((0, 1), (1, 0), (0, -1), (-1, 0)):
            for k in range(1, K + 1):
                x2 = x1 + dx * k
                y2 = y1 + dy * k

                if (0 <= x2 < H) and (0 <= y2 < W):
                    if m[x2][y2] == '@':
                        break
                    elif M[x2][y2] == -1:
                        q.append((d + 1, x2, y2))
                    elif M[x2][y2] < d + 1:
                        break
                else:
                    break
    print(-1)


H, W, K = map(int, input().split())
xs, ys, xg, yg = map(int, input().split())
xs, ys, xg, yg = xs - 1, ys - 1, xg - 1, yg - 1

m = []
for i in range(H):
    m.append(list(map(str, sys.stdin.readline().strip())))

M = [[-1] * W for i in range(H)]

bfs(xs, ys, 0)


### FIXED CODE ###

from collections import deque


def bfs(maze, visited, sy, sx, gy, gx):
    queue = deque([[sy, sx]])
    visited[sy][sx] = 0
    while queue:
        # queueには訪れた地点が入っている。そこから、4方向に移動できるか考え、queueから消す。
        y, x = queue.popleft()  # queueに入っていたものを消す。
        if [y, x] == [gy, gx]:  # もしゴールについていたならば、そのときの手数を出す。
            return visited[y][x]
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            l = 1
            while True:
                new_y, new_x = y + j * l, x + k * l
                if (0 <= new_y < H) and (0 <= new_x < W):
                    if maze[new_y][new_x] == "@":
                        break
                    elif visited[new_y][new_x] == -1:  # まだ来たことない点だったという条件
                        visited[new_y][new_x] = visited[y][x] + 1
                        queue.append([new_y, new_x])  # 新しい点を足す。
                    elif visited[new_y][new_x] < visited[y][x] + 1:
                        break
                else:
                    break
                l += 1
                if l == K + 1:
                    break


H, W, K = map(int, input().split())
# K = min(K, max(H, W))
x1, y1, x2, y2 = map(int, input().split())
x1, y1, x2, y2 = x1 - 1, y1 - 1, x2 - 1, y2 - 1
C = [0] * H
for i in range(H):
    C[i] = str(input())
visited = [[-1] * W for i in range(H)]
bfs(C, visited, x1, y1, x2, y2)
# print(visited)
print(visited[x2][y2])
### BUGGY CODE ###

# -*- coding: utf-8 -*-
H, W, D = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(H)]
Q = int(input())
LR = [list(map(int, input().split())) for _ in range(Q)]

xy = {}
for h in range(H):
    for w in range(W):
        xy[A[h][w]] = (h,w)

for l,r in LR:
    if l == r:
        print(0)
        continue

    start = l
    cost = 0
    while start != r:
        x,y = xy[start]
        i,j = xy[start+D]
        cost += abs(x-i) + abs(y-j)
        start += D

    print(cost)


### FIXED CODE ###

# -*- coding: utf-8 -*-
import math
from pprint import pprint

H, W, D = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(H)]
Q = int(input())
LR = [list(map(int, input().split())) for _ in range(Q)]

xy = {}
for h in range(H):
    for w in range(W):
        xy[A[h][w]] = (h,w)

xy[0] = xy[D]

width = math.ceil(H*W/D)
rui_xy = [[0 for _ in range(width+1)] for _ in range(D)]
for d in range(D):
    rui_cost = 0
    x,y = xy[d]
    for w in range(width+1):
        if w*D+d > H*W:
            break
        i,j = xy[w*D+d]
        rui_cost += abs(x-i) + abs(y-j)
        rui_xy[d][w] = rui_cost
        x,y = i,j

for l,r in LR:
    if l == r:
        print(0)
        continue

    print(rui_xy[r % D][r//D] - rui_xy[l % D][l//D])
### BUGGY CODE ###

N, A = map(int, input().split())
X = [int(x) for x in input().split()]
X.sort()
ans = 0
for i in range(1, 2 ** N):
  mask = bin(i)[2:]
  mask = [0 for x in range(N - len(mask))] + [int(s) for s in mask]
  if sum([X[j] * mask[j] for j in range(N)]) / sum(mask) == A:
    ans += 1
print(ans)

### FIXED CODE ###

from collections import Counter
N, A = map(int, input().split())
X = [int(x) - A for x in input().split()]
C = Counter([0])
for x in X:
  tmp = Counter()
  for i, c in C.items():
    tmp[i + x] += c
  C += tmp
print(C[0] - 1)
### BUGGY CODE ###

c = 0
input()
s = input().split()
input()
t = input().split()
for make in t :
    if make in s : c += 1
print(c)

### FIXED CODE ###

c = 0
input()
s = set(input().split())
input()
t = set(input().split())
print(len(s&t))
### BUGGY CODE ###

import sys
input = sys.stdin.readline
H,W=map(int,input().split())
s=[]
s.append("".join("#" for _ in range(W+2)))
cnt=0
for i in range(H):
    ss=input().strip()
    s.append("#"+ss+"#")
    for w in range(W):
        if ss[w]==".":
            cnt+=1

s.append("".join("#" for _ in range(W+2)))
#print(s)
import sys
sys.setrecursionlimit(300000)
def solv(h,w,cnt):
    #print(h,w)
    #print(a)
    #print(s)
    if a[h][w]>cnt+1 and s[h][w]==".":
        a[h][w]=cnt+1
        solv(h-1,w,cnt+1)
        solv(h,w-1,cnt+1)
        solv(h+1,w,cnt+1)
        solv(h,w+1,cnt+1)
    return

a=[[1000000]*(W+2) for _ in range(H+2)]
solv(1,1,0)
print(cnt-a[-2][-2] if a[-2][-2]!= 1000000 else -1)


### FIXED CODE ###

import sys
input = sys.stdin.readline
H,W=map(int,input().split())
s=[]
s.append("".join("#" for _ in range(W+2)))
cnt=0
for i in range(H):
    ss=input().strip()
    s.append("#"+ss+"#")
    for w in range(W):
        if ss[w]==".":
            cnt+=1

s.append("".join("#" for _ in range(W+2)))
#print(s)
import sys
sys.setrecursionlimit(300000)
def solv(h,w,cnt):
    #print(h,w)
    #print(a)
    #print(s)
    if a[h][w]>cnt+1 and s[h][w]==".":
        a[h][w]=cnt+1
        solv(h-1,w,cnt+1)
        solv(h,w-1,cnt+1)
        solv(h+1,w,cnt+1)
        solv(h,w+1,cnt+1)
    return

a=[[1000000]*(W+2) for _ in range(H+2)]
solv(1,1,0)
print(cnt-a[-2][-2] if a[-2][-2]!= 1000000 else -1)
### BUGGY CODE ###

import heapq

n, m = map(int, input().split())
a = list(map(int, input().split()))
bc = [list(map(int, input().split())) for _ in range(m)]
bc = sorted(bc, reverse = True, key = lambda x: x[1])
heapq.heapify(a)

for bbcc in bc:
  for _ in range(bbcc[0]):
    if a[0] < bbcc[1]:
      heapq.heappop(a)
      heapq.heappush(a, bbcc[1])

print(sum(a))

### FIXED CODE ###

import heapq

n, m = map(int, input().split())
a = list(map(int, input().split()))
bc = [list(map(int, input().split())) for _ in range(m)]
bc = sorted(bc, reverse = True, key = lambda x: x[1])
heapq.heapify(a)

for bbcc in bc:
  if a[0] >= bbcc[1]:
    break

  for _ in range(bbcc[0]):
    if a[0] < bbcc[1]:
      heapq.heappop(a)
      heapq.heappush(a, bbcc[1])
    else:
      break

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

n = int(input())
a = [int(x) for x in input().split()]
ans = 10**10
suma = sum(a)
for i in range(1, n):
    x = sum(a[:i])
    s = abs(x-(suma-x))
    if s < ans:
        ans = s
print(ans)

### FIXED CODE ###

n = int(input())
a = [int(x) for x in input().split()]

x = a[0]
y = sum(a[1:])
ans = abs(x-y)

for i in range(1, n-1):
    x += a[i]
    y -= a[i]
    ans = min(ans, abs(x-y))
print(ans)
### BUGGY CODE ###

import copy
N = int(input())
A = [list(map(int,input().split())) for i in range(N)]
cost = copy.deepcopy(A)
edge = copy.deepcopy(A)
for k in range(N):
    for i in range(N):
        for j in range(i):
            if i != k and j != k:
                if cost[i][j] == cost[i][k]+cost[k][j]:
                    edge[i][j] = 0
                if cost[i][j] > cost[i][k]+cost[k][j]:
                    cost[i][j] = cost[i][k]+cost[k][j]
ans = True
for i in range(N):
    for j in range(i):
        if A[i][j] != cost[i][j]:
            ans = False
            break
if not ans:
    print(-1)
else:
    ans = 0
    for i in range(N):
        for j in range(i):
            ans += edge[i][j]
    print(ans)

### FIXED CODE ###

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

from scipy.sparse.csgraph import floyd_warshall as fw
import numpy as np
a = fw(A)
ans = 0
for i in range(N):
    a[i][i] = np.inf
for i in range(N):
    for j in range(i):
        if A[i][j]!=a[i][j]:
            print(-1)
            exit()
        else:
            if a[i][j] < np.min(a[i]+a[j]):
                ans += a[i][j]
print(int(ans))
### BUGGY CODE ###

# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
from collections import deque
import sys
def main(N, M, G, root):
    P = [-1] * N
    D = [-1] * N
    q = deque()
    q.append((root, 0, -1))
    while q:
        v, d, p = q.popleft()
        if D[v] < d:
            D[v] = d
            P[v] = p
        for to in G[v]:
            q.append((to, d + 1, v))
    for p in P:
        print(p + 1)

if __name__ == '__main__':
    input = sys.stdin.readline
    N, M = map(int, input().split())
    G = [[] for _ in range(N)]
    I = [0] * N
    for _ in range(N - 1 + M):
        a, b = map(int, input().split())
        a, b = a - 1, b - 1
        G[a].append(b)
        I[b] += 1
    main(N, M, G, I.index(0))


### FIXED CODE ###

# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
from collections import deque
import sys
def main(N, M, G, R, I, root):
    P = [-1] * N
    D = [-1] * N
    D[root] = 0
    q = deque()
    q.append(root)
    while q:
        v = q.popleft()
        for to in G[v]:
            I[to] -= 1
            if I[to] == 0:
                p = pd = -1
                for r in R[to]:
                    if D[r] > pd:
                        pd = D[r]
                        p = r
                D[to] = pd + 1
                P[to] = p
                q.append(to)
    for p in P:
        print(p + 1)

if __name__ == '__main__':
    input = sys.stdin.readline
    N, M = map(int, input().split())
    G = [[] for _ in range(N)]
    R = [[] for _ in range(N)]
    I = [0] * N
    for _ in range(N - 1 + M):
        a, b = map(int, input().split())
        a, b = a - 1, b - 1
        G[a].append(b)
        R[b].append(a)
        I[b] += 1
    main(N, M, G, R, I, I.index(0))
### BUGGY CODE ###

import numpy as np
import sys
sysinput = sys.stdin.readline

N = int(sysinput())
P = np.array(list(map(int, sysinput().split())))

i_count = 1
for i in range(1, N):
  if (P[:i] < P[i]).any() == False:
    i_count +=1
  
print(i_count)

### FIXED CODE ###

import sys
sysinput = sys.stdin.readline

N = int(sysinput())
P = list(map(int, sysinput().split()))
memo_mini = N
i_count = 0
for i in range(0, N):
  if memo_mini >= P[i]:
      i_count +=1
      memo_mini = P[i]
  else:
    pass
  
print(i_count)
### BUGGY CODE ###

# -*- coding: utf-8 -*-
n = int(input())
vl = list(map(int, input().split()))
cl = list(map(int, input().split()))

res = -1

for i in range(2**n):
    x = 0
    y = 0
    for j in range(n):
        if i>>j&1==1:
            x += vl[j]
            y += cl[j]
    res = max(res, x-y)

print(res)


### FIXED CODE ###

# -*- coding: utf-8 -*-
n = int(input())
vl = list(map(int, input().split()))
cl = list(map(int, input().split()))

res = -1

for i in range(2**n):
    x = 0
    y = 0
    for j in range(n):
        if i>>j&1==1:
            x += vl[j]
            y += cl[j]
    res = max(res, x-y)

print(res)
### BUGGY CODE ###

from functools import reduce
from fractions import gcd
import numpy as np

MOD = 10**9+7

def lcm_base(x, y):
    return (x * y) // gcd(x, y)


def main():
    N = int(input())
    a = [int(i) for i in input().split()]
    A = np.array(a)

    lcm = reduce(lcm_base, a, 1)
    B = lcm // A

    print(np.sum(B) % MOD)


if __name__ == "__main__":
    main()


### FIXED CODE ###

from functools import reduce
from fractions import gcd

MOD = 10**9+7

def lcm_base(x, y):
    return (x * y) // gcd(x, y)

def main():
    N = int(input())
    a = [int(i) for i in input().split()]

    lcm = reduce(lcm_base, a, 1)
    
    ans = 0
    for i in a:
        ans += lcm // i

    print(ans % MOD)


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

M = 1000000007

def nCr(n, k): 
    C = [[0 for x in range(k+1)] for x in range(n+1)] 
  
    for i in range(n+1): 
        for j in range(min(i, k)+1): 
            if j == 0 or j == i: 
                C[i][j] = 1
  
            else: 
                C[i][j] = C[i-1][j-1] + C[i-1][j] 
  
    return C[n][k] 

x, y , z = map(int,input().split()) 
ans = pow(2,x)-1
ans = ans - nCr(x,y)
ans = ans - nCr(x,z)
ans = ans%M

print(int(ans))


### FIXED CODE ###

def nrc_mod(n, r, mod=10**9+7):
    r = min(n - r, r)
    if r == 0:
        return 1
 
    over = 1
    for i in range(n, n - r, -1):
        over = over * i % mod
 
    under = 1
    for i in range(1, r + 1):
        under = under * i % mod
 
    inv = pow(under, mod - 2, mod)
    return over * inv % mod
 
 
n, a, b = map(int, input().split())
MOD = 10**9 + 7

ans = pow(2, n, MOD) - 1
ans -= nrc_mod(n, a, MOD)
ans -= nrc_mod(n, b, MOD)
while ans < 0:
    ans += MOD
print(ans)
### BUGGY CODE ###

N = int(input())
a = [int(i) for i in input().split()]
i = 0
b = []
while i <= 100000:
  n = a.count(i)
  b.append(n)
  i += 1
l = len(b)
j = 1
c = []
while j < l-1:
  nn = b[j-1]+b[j]+b[j+1]
  c.append(nn)
  j += 1
print(max(c))

### FIXED CODE ###

N = int(input())
A = list(map(int, input().split()))
dic = {}
for nums in A:
  if nums in dic:
    dic[nums] += 1
  else:
    dic[nums] = 1
  if nums-1 in dic:
    dic[nums-1] += 1
  else:
    dic[nums-1] = 1
  if nums+1 in dic:
    dic[nums+1] += 1
  else:
    dic[nums+1] = 1
b = list(dic.values())
print(max(b))
### BUGGY CODE ###

from  functools import lru_cache

@lru_cache(maxsize = 2**17)
def get_coord(num, H, W, masu):
    for i in range(H):
        for j in range(W):
            if masu[i][j] == num:
                return i, j

H, W, D = map(int, input().split())
masu = [[] for i in range(H)]
for i in range(H):
    masu[i] = tuple([int(i) for i in input().split()])
masu = tuple(masu)
Q = int(input())

exam = [[] for i in range(Q)]
for i in range(Q):
    exam[i] = [int(i) for i in input().split()]

for i in range(Q):
    reduce_MP = 0
    num = exam[i][0]
    coord1 = get_coord(num, H, W, masu)
    while num < exam[i][1]:
        coord2 = get_coord(num + D, H, W, masu)
        reduce_MP += abs(coord1[0] - coord2[0]) + abs(coord1[1] - coord2[1])
        num += D
        coord1 = coord2
    print(reduce_MP)



### FIXED CODE ###

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

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

xx = [0 for i in range(90002)]
yy = [0 for i in range(90002)]
for y in range(H):
    for x in range(W):
        xx[Amap[y][x]] = x
        yy[Amap[y][x]] = y
Q = int(input())

coord = []
for i in range(Q):
    coord.append(list(map(int, input().split())))

# magic point calculation
mp = [0 for i in range(90002)]

for i in range(D+1, 90002):
    mp[i] = mp[i-D] + abs(xx[i] -xx[i-D]) + abs(yy[i] - yy[i-D])

for i in coord:
    print(mp[i[1]] - mp[i[0]])
### BUGGY CODE ###

n, m = map(int, input().split())
a = map(int, input().split())
q = []
for i in a:
    q.append(i)
for i in range(m):
    b, c = map(int, input().split())
    for j in range(b):
        q.append(c)
print(sum(sorted(q)[-n:]))


### FIXED CODE ###

n, m = map(int, input().split())
a = [[1, int(x)] for x in input().split()]
bc = [list(map(int, input().split())) for x in range(m)]
a.extend(bc)
a = sorted(a, key=lambda x: x[1], reverse=True)
d = []
ans = 0
cnt = 0
for x in a:
    if cnt > n:
        break
    k = x[0]
    if cnt + k > n:
        k = n - cnt
    ans += x[1] * k
    cnt += k
print(ans)
### BUGGY CODE ###

from collections import Counter
N = int(input())
A = Counter(list(map(int, input().split(' '))))
ans = 0
for i in A.keys():
    flg = True
    if A[i] > 1:
        continue
    for j in range(1,int(i**0.5)+2):
        if not i%j:
            if j != i//j:
                if A[i//j] and i//j != i:
                    flg = False
                    break
            if A[j] and i != j:
                flg = False
                break
    if flg:
        ans += 1
print(ans)

### FIXED CODE ###

from collections import Counter
N = int(input())
A = Counter(list(map(int,input().split(' '))))
ans = 0
m = max(A.keys())
L = [1]*(10**6+1)
for i in sorted(A.keys()):
    if not L[i]:
        continue
    if A[i] == 1:
        ans += 1
    for j in range(i,m+1,i):
        L[j] = 0
print(ans)
### BUGGY CODE ###

from functools import lru_cache
arr=[]
n,w=map(int,input().split())
for _ in range(n):
	arr.append(tuple(map(int,input().split())))
@lru_cache(maxsize=10000000)
def f(pos,W):
	if(pos==n):
		return 0
	res=f(pos+1,W)
	if(arr[pos][0]<=W):
		res=max(res,f(pos+1,W-arr[pos][0])+arr[pos][1])
	return res
print(f(0,w))

### FIXED CODE ###

import numpy as np 
IN = lambda:map(int, input().split())
 
n, k = IN()
dp = np.zeros(k + 1)
 
for i in range(n):
    w, c = IN()
    dp[w:] = np.maximum(dp[w:], dp[:-w] + c)
    
print(int(dp[-1]))
### BUGGY CODE ###

n=int(input())
a=list(map(int,input().split()))
a.sort()
ans=1
for i in range(n-1):
    k=1
    while a[i]+2>=a[i+k]:
        k+=1
        if i+k>=n:
            break
    ans=max(ans,k)
print(ans)

### FIXED CODE ###

from collections import Counter as C
n=int(input())
a=list(map(int,input().split()))
a.sort()
aset=list(set(a))
ca = C(a)
ans=0
for i in aset:
    if ans<ca[i-1]+ca[i]+ca[i+1]:
        ans=ca[i-1]+ca[i]+ca[i+1]
print(ans)