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

import sys

A=[[0,0,0]]
size = 0

def insert(A,x):
    global size

    fp=A[0][1]
    try:
        i=[e[0] for e in A].index(-1)
        A[i]=[x,fp,0]
        A[fp][2]=i
        A[0][1]=i
    except:
        A.append([x,fp,0])
        A[fp][2]=len(A)-1
        A[0][1]=len(A)-1     
    size += 1    

def delete(A,x):
    global size
    p =A[0][1]
    while A[p][0]!=x:
        p=A[p][1]
        if p==0: return
    fp=A[p][1]
    bp=A[p][2]
    A[fp][2]=bp
    A[bp][1]=fp
    A[p]=[-1,-1,-1]
    size -= 1
    return

def deletefirst(A):
    global size
    if size == 0: return
    p=A[0][1]
    fp=A[p][1]
    A[0][1]=fp
    A[fp][2]=0
    A[p]=[-1,-1,-1]
    size -= 1
    return 0

def deletelast(A):
    global size
    if size == 0: return
    p=A[0][2]
    bp=A[p][2]
    A[0][2]=bp
    A[bp][1]=0
    A[p]=[-1,-1,-1]
    size -= 1
    return 0

n = int(raw_input())
for i in range(n):
    s = (raw_input().split())
    if s[0] == 'insert':
        insert(A,s[1])
    elif s[0] == 'delete':
        delete(A,s[1])
    elif s[0] == 'deleteFirst':
        deletefirst(A)
    elif s[0] == 'deleteLast':
        deletelast(A)

e = A[0][1]
while e!=0:
    print A[e][0],
    e = A[e][1]

### FIXED CODE ###

import sys,gc
    
A=[]
fp =0
bp =0

n=int(raw_input())
while n:
    s = raw_input()
    if s[0] == 'i':
        A.append(int(s[7:]))
        fp += 1
    elif s[6] == ' ':
        try:
            i = A[::-1].index(int(s[7:]))
            if i!=-1:
                del A[-i-1]
                fp -=1
        except:
            pass
    elif s[6] == 'F':
        A.pop()
        fp -=1
    elif s[6] == 'L':
        bp +=1
    n -=1

for e in A[bp:fp+1][::-1]:
    print int(e),
### BUGGY CODE ###

from collections import deque
import copy
def main():
  n = int(input())
  p = list(map(int, input().split()))
  for i in range(len(p)):
      p[i] -= 1

  to_outsides = [[0 for _ in range(n)] for _ in range(n)]
  not_exist = [["■" for _ in range(n)] for _ in range(n)]


  for i in range(n):
      for j in range(n):
          to_outside = [i,n-1-i,j,n-1-j]
          to_outsides[i][j] = min(to_outside)

  directions = [[-1,0],[1,0],[0,-1],[0,1]]

  all_loss = 0
  answer = 0
  for i, person in enumerate(p):
      exited = [person//n, person%n]
      answer += to_outsides[exited[0]][exited[1]]
      not_exist[exited[0]][exited[1]] = "□"
      seen = []
      seen.append([exited[0],exited[1]])
      todo = deque([exited])
      renews = []
      while len(todo)>0:
          now = todo.pop()
          renews.append(now)
          for direction in directions:
              try:
                  checking = [now[0]+direction[0],now[1]+direction[1]]
                  to_outsides[checking[0]][checking[1]]
              except:
                  continue
              if [checking[0],checking[1]] not in seen and\
              ((not_exist[checking[0]][checking[1]] == "□" and  to_outsides[checking[0]][checking[1]]==to_outsides[now[0]][now[1]])or\
              to_outsides[checking[0]][checking[1]]>to_outsides[now[0]][now[1]]):
                  todo.append([checking[0],checking[1]])
                  seen.append([checking[0],checking[1]])

      for renew in renews:
          if to_outsides[renew[0]][renew[1]] != 0:
              to_outsides[renew[0]][renew[1]]-=1
  print(answer)

main()


### FIXED CODE ###

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

dp = [[min(i, N - i - 1, j, N - j - 1) for j in range(N)] for i in range(N)]

presence = [[1 for j in range(N)] for i in range(N)]

ans = 0
for i in range(len(P)):
    P[i] -= 1
    x, y = divmod(P[i], N)
    ans += dp[x][y]
    presence[x][y] = 0

    Q = [(x, y)]
    #%%
    while Q:
        x, y = Q.pop()
        new_value = dp[x][y] + presence[x][y]
        if 1 <= x and dp[x - 1][y] > new_value:
            dp[x - 1][y] = new_value
            Q.append((x - 1, y))
        if x < N - 1 and dp[x + 1][y] > new_value:
            dp[x + 1][y] = new_value
            Q.append((x + 1, y))
        if 1 <= y and dp[x][y - 1] > new_value:
            dp[x][y - 1] = new_value
            Q.append((x, y - 1))
        if y < N - 1 and dp[x][y + 1] > new_value:
            dp[x][y + 1] = new_value
            Q.append((x, y + 1))

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

import bisect
import copy
import heapq
import math
import sys
from collections import *
from itertools import accumulate, combinations, permutations, product
# from math import gcd
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

n,m,p=map(int,input().split())
abc=[list(map(int,input().split())) for i in range(m)]

edge=defaultdict(list)
coin=defaultdict(int)
for i in range(m):
    a,b,c=abc[i]
    edge[a].append(b)
    coin[(a,b)]=max(coin[(a,b)],c)
# print(edge,coin)

itta=[-float('inf')]*(n+1)
d=deque([[1,0,itta[:]]])
infdic=defaultdict(int)
while d:
    now,c,itta=d.popleft()
    if itta[now]==-float('inf'):
        itta[now]=c
        for i in edge[now]:
            d.append([i,c+coin[(now,i)]-p,itta[:]])
    else:
        if itta[now]<c:
            infdic[now]=float('inf')

# print(infdic)

itta=[0]*(n+1)
d=deque([[1,0,itta[:]]])
ans=0
while d:
    now,c,itta=d.popleft()
    c=max(c,infdic[now])
    if now==n:
        ans=max(ans,c)
    
    if itta[now]==0:
        itta[now]=1
        for i in edge[now]:
            d.append([i,c+coin[(now,i)]-p,itta[:]])

if ans==float('inf'):
    print(-1)
else:
    print(max(ans,0))

### FIXED CODE ###

import bisect
import copy
import heapq
import math
import sys
from collections import *
from itertools import accumulate, combinations, permutations, product
# from math import gcd
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

n,m,p=map(int,input().split())
abc=[list(map(int,input().split())) for i in range(m)]

#True : 負の経路が存在する
def find_negative_loop1(n,w,es):
    #負の経路の検出
    #n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [float("inf")] * n
    d[0] = 0
    infdic=defaultdict(int)
    #この始点はどこでもよい
    for i in range(n):
        for j in range(w):
            e = es[j]
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i == n-1:
                    infdic[e[0]]=1
    return infdic

def find_negative_loop2(n,w,es,infd):
    #負の経路の検出
    #n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [float("inf")] * n
    d[0] = 0
    for i in infd.keys():
        d[i]=-float('inf')
    #この始点はどこでもよい
    for i in range(n):
        for j in range(w):
            e = es[j]
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                # if i == n-1:
                #     return True
    return d


#############################
w = m
es = [[] for i in range(w)] #es[i]: [辺の始点,辺の終点,辺のコスト]
for i in range(w):
    x,y,z = abc[i]
    es[i] = [x-1,y-1,p-z]
# w = w*2
# print(es)

tmp=find_negative_loop1(n,w,es)
# print(tmp)
tmp2=find_negative_loop2(n,w,es,tmp)
# print(tmp2)
if tmp2[-1]==-float('inf'):
    print(-1)
else:
    print(-min(tmp2[-1],0))
### BUGGY CODE ###

N = int(input())
A = list(map(int, input().split()))
d = {}
for i in A:
    if i in d.keys():
        d[i] += 1
    else:
        d[i] = 1
whole_ans = sum(map(lambda x: x*(x-1)//2, d.values()))
for i in A:
    d_ = d.copy()
    d_[i] -= 1
    dif = (d_[i]*(d_[i]-1) - d[i]*(d[i]-1)) // 2
    part_ans = whole_ans + dif
    print(part_ans)

### FIXED CODE ###

N = int(input())
A = list(map(lambda x: int(x)-1, input().split()))
d = [0] * N
for i in A:
    d[i] += 1
s = sum(map(lambda x: x*(x-1)//2, d))
for i in A:
    print(s + (1 - d[i]))
### BUGGY CODE ###

import numpy as np

N = int(input())
A = np.array(list(map(int, input().split())))
Q = int(input())

for i in range(Q):
    B,C = (int(x) for x in input().split())

    idx_list = [i for i, x in enumerate(A) if x == B]
    for idx in idx_list:
        A[idx]=C
    
    print(sum(A))


### FIXED CODE ###

# 371 ms, 27032 KB
n = int(input())
a = list(map(int, input().split()))
q = int(input())
b = []
c = []
 
bc = [map(int, input().split()) for _ in range(q)]
b, c = [list(i) for i in zip(*bc)]
 
dic = {}
for aa in a:
    dic[aa] = dic.get(aa, 0) + 1
 
s = sum(a)
for i in range(q):
    if b[i] not in dic:
        print (str(s))
        continue
    s += (c[i]-b[i]) * dic[b[i]]
    dic[c[i]] = dic.get(c[i], 0) + dic[b[i]]
    del dic[b[i]]
    print(s)
### BUGGY CODE ###

import math
from collections import deque
n,m=[int(_) for _ in input().split()]
A=[[int(_) for _ in input().split()] for l in range(m)]
R=deque([] for _ in range(n))
for a in A:
    R[a[0]-1].append(a[1]-1)
    R[a[1]-1].append(a[0]-1)
print("Yes")
for h in range(1,n):
    dq=deque()
    dq.appendleft([h])
    while dq:
        x=dq.popleft()
        if 0 in R[x[-1]]:
            if len(x)==1:
                print(1)
            else:
                print(x[1]+1)
            break
        for a in R[x[-1]]:
            dq.append(x+[a])



### FIXED CODE ###

import math
from collections import deque
n,m=[int(_) for _ in input().split()]
A=[[int(_) for _ in input().split()] for l in range(m)]
R=deque([] for _ in range(n))
for a in A:
    R[a[0]-1].append(a[1]-1)
    R[a[1]-1].append(a[0]-1)
print("Yes")
Dis=deque([100000000]*n)
Dis[0]=0
PP=deque([0]*n)
l=deque()
l.append(0)
while l:
    x=l.popleft()
    for a in R[x]:
        if Dis[a]>Dis[x]+1:
            Dis[a]=Dis[x]+1
            l.append(a)
            PP[a]=x
for t in range(1,n):
    print(PP[t]+1)
### BUGGY CODE ###

N = int(input())

cnt = 0
start = 2
z = 1

#nの素数判定
def is_prime(n):
    if n == 1:
        return False
    for i in range(2,int(n**0.5)+1):
        if n % i == 0:
            return False
    return True

# 素因数分解の関数
def prime_factorize(n):
    a = []
    while n % 2 == 0:
        a.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            a.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        a.append(n)
    return a
    
if is_prime(N) == False:
    while N != 1:
        for i in range(start, N+1):
            prime = prime_factorize(i)
            if N % i == 0 and prime[0] == prime[-1]:
                z = i
                start = i+1
                cnt += 1
                break
        # cnt += 1
        N = N // z
        # print(z, N, start)
        if z >= N:
            break
    print(cnt)

# 素数の時は必ず1
else:
    print(1)


### FIXED CODE ###

N = int(input())

cnt = 0
result = 0

num = [1,3,6,10,15,21,28,36,45,55,66]

def prime_factorize(n):
    """[summary]
    素因数分解の関数、整数を入力して配列を返す
    計算量はO(√N)
    Arguments:
        n {[int]} -- 素進数分解するための整数

    Returns:
        list -- 素因数分解した後の数字の配列
    """    
    a = []
    while n % 2 == 0:
        a.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            a.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        a.append(n)
    return a

def factorization(n):
    """[summary]
    素因数分解して、素数の種類とその素数の個数を二次元配列に入れる
    Arguments:
        n {int} -- 素因数分解する整数

    Returns:
        [arr] -- [[素数, 個数], [素数, 個数], ... ]
    """    
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])
 
    if temp!=1:
        arr.append([temp, 1])
 
    if arr==[]:
        arr.append([n, 1])
 
    return arr


L = factorization(N)

if N == 1:
    print(0)
else:
    for p,e in L:
        cnt = 1
        for i in range(2,100):
            cnt += i
            if e < cnt:
                result += i-1
                break
                
    print(result)
### BUGGY CODE ###

import numpy as np
import math

def Split(cum_):
    S_ = cum_[-1]
    idx_ = np.argmin(np.abs(S_ - 2 * cum_))
    cum1_ = cum_[:idx_ + 1]
    cum2_ = cum_[idx_ + 1:] - cum_[idx_]
    return cum1_[-1], cum2_[-1]


N = int(input())
A = np.array(list(map(int, input().split())))
CumA = np.cumsum(A)

res = 10 ** 15
for i in range(1, N-2):
    P, Q = Split(CumA[: i+1])
    R, S = Split(CumA[i+1:] - CumA[i])
    res = min(res, max([P, Q, R, S]) - min([P, Q, R, S]))
print(res)

### FIXED CODE ###

# -*- coding: utf-8 -*-
from sys import stdin
import numpy as np

d_in = lambda: int(stdin.readline())  # N = d_in()
ds_in = lambda: list(map(int, stdin.readline().split()))  # List = ds_in()


def left_diff(array):
    """
    array: ordered ndarray, len(array) >= 2
    """
    x = (array[-1] + 1) >> 1
    mid = np.searchsorted(array, x)
    if abs(array[-1] - array[mid] * 2) < abs(array[-1] - array[mid-1] * 2):
        return array[mid], array[-1] - array[mid]
    else:
        return array[mid-1], array[-1] - array[mid-1]


def right_diff(array, offset):
    """
    array: ordered ndarray, len(array) >= 2
        target array or list

    offset: int
        offset value for right array
    """
    x = (array[-1] - offset + 1) >> 1
    mid = np.searchsorted(array, x + offset)
    if abs(array[-1] - array[mid] * 2 + offset)\
            < abs(array[-1] - array[mid-1] * 2 + offset):
        return array[mid] - offset, array[-1] - array[mid]
    else:
        return array[mid-1] - offset, array[-1] - array[mid-1]


def calc_max_diff(p, q, r, s):
    return max(p, q, r, s) - min(p, q, r, s)


if __name__ == '__main__':
    N = d_in()
    a_array = np.array(ds_in())

    cum_a = np.cumsum(a_array)
    left_cut_points = (cum_a[1:-2] + 1) // 2
    left_mid_points = np.searchsorted(cum_a, left_cut_points)
    right_cut_points = (cum_a[-1] + cum_a[1:-2] + 1) // 2
    right_mid_points = np.searchsorted(cum_a, right_cut_points)
    
    ans = float('inf')
    for i in range(2):
        for j in range(2):
            P = cum_a[left_mid_points-i]
            Q = cum_a[1:-2] - P
            R = cum_a[right_mid_points-j] - cum_a[1:-2]
            S = cum_a[-1] - cum_a[right_mid_points-j]
            MAX = np.maximum(np.maximum(P, Q), np.maximum(R, S))
            MIN = np.minimum(np.minimum(P, Q), np.minimum(R, S))
            ans = min(ans, (MAX - MIN).min())

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

import math
K=int(input())
sum=0
for a in range(1,K+1):
    for b in range(1,K+1):
        for c in range(1,K+1):           
            ans = math.gcd(a, b)
            ans=math.gcd(ans,c)
            sum+=ans
print(sum)

### FIXED CODE ###

from math import gcd
K=int(input())
sum=0
for a in range(1,K+1):
    for b in range(1,K+1):
        for c in range(1,K+1):           
            
            sum+=gcd(gcd(a,b),c)
print(sum)
### BUGGY CODE ###

def lucas(n):
    if n==0:
        return 2
    elif n==1:
        return 1
    else:
        return lucas(n-1)+lucas(n-2)
n= int(input())
print(lucas(n))

### FIXED CODE ###

n=int(input())
a,b,c=2,1,3
if n==0:
    print(2)
elif n==1:
    print(1)
elif n==2:
    print(3)
else:
    for i in range(n-2):
        a,b,c=b,c,b+c
    print(c)
### BUGGY CODE ###

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

ans = 0

for x in range(M+1):
    if x%2 == 0:
        ans = max(ans,min(N+x//2,(M-x)//2))
    
print(ans)

### FIXED CODE ###

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

if M-2*N >= 0:
    print(N + (M-2*N)//4)
else:
    print(M//2)
### BUGGY CODE ###

#### import ####
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):
  read_all = [tuple(map(int, input().split())) for _ in range(N)]
  return map(list,zip(*read_all))

#################

def Z_algo(S):
  n=len(S)
  A=[0]*n
  A[0]=n
  i=1
  j=0
  while i<n:
    while i+j<n and S[j]==S[i+j]: j+=1
    A[i]=j
    if j==0:
      i+=1
      continue
    k=1
    while i+k<n and k+A[k]<j:
      A[i+k]=A[k]
      k+=1
    i+=k
    j-=k
  return A

def dfs(pt,v,visited):
  if visited[v]==True:
    return -1,visited
  n=len(pt)
  d=[-1]*n
  check_visited = [False]*n
  check_visited[v] = True
  S = [v]
  d[v] = 0
  while S:
    v1 = S.pop()
    for i in pt[v1]:
      if check_visited[i] == False:
        check_visited[i] = True
        visited[i] = True
        d[i] = d[v1] + 1
        S.append(i)
      else:
        print(-1)
        exit()
  return max(d),visited

s = str(input())
t = str(input())

ls = len(s)
lt = len(t)

s2 = t + s*(lt//ls +2)
A = Z_algo(s2)

B = [False]*ls
for i in range(ls):
  if A[i+lt]>=lt:
    B[i]=True

pt = [[] for _ in range(ls)]
for i in range(ls):
  if B[i]==True:
    pt[i].append((i+lt)%ls)

visited = [False]*ls

ans = 0
for v in range(ls):
  if B[v]:
    tmp,visited = dfs(pt,v,visited)
    if tmp>ans:
      ans = tmp

print(ans)

### FIXED CODE ###

#### import ####
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):
  read_all = [tuple(map(int, input().split())) for _ in range(N)]
  return map(list,zip(*read_all))

#################

def Z_algo(S):
  n=len(S)
  A=[0]*n
  A[0]=n
  i=1
  j=0
  while i<n:
    while i+j<n and S[j]==S[i+j]: j+=1
    A[i]=j
    if j==0:
      i+=1
      continue
    k=1
    while i+k<n and k+A[k]<j:
      A[i+k]=A[k]
      k+=1
    i+=k
    j-=k
  return A

def dfs(pt,v,visited):
  if visited[v]==True:
    return -1,visited
  S = [v]
  now = 0
  while S:
    v1 = S.pop()
    for i in pt[v1]:
      if i != v:
        visited[i] = True
        now += 1
        S.append(i)
      else:
        print(-1)
        exit()
  return now,visited

s = str(input())
t = str(input())

ls = len(s)
lt = len(t)

s2 = t + s*(lt//ls +2)
A = Z_algo(s2)

B = [False]*ls
for i in range(ls):
  if A[i+lt]>=lt:
    B[i]=True

pt = [[] for _ in range(ls)]
for i in range(ls):
  if B[i]==True:
    pt[i].append((i+lt)%ls)

visited = [False]*ls

ans = 0
for v in range(ls):
  if B[v]:
    tmp,visited = dfs(pt,v,visited)
    if tmp>ans:
      ans = tmp

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

s=input()
q= int(input())

for iq in range(1,q+1):
	t=input().split()
	if t[0]=='1':
		s=s[::-1]
	else:
		if t[1]=='1':
			s=t[2]+s
		else:
			s=s+t[2]   
print (s)

### FIXED CODE ###

s=input()
q= int(input())

top=""
btm=""

iturn=0
for iq in range(1,q+1):
	t=input().split()
	if t[0]=='1':
		iturn=iturn+1   	
	else:
		iturn2=iturn%2
		if (t[1]=='1' and iturn2==0) or (t[1]=='2' and iturn2==1):
#			s=t[2]+s
#			s='{}{}'.format(t[2],s)
			top=t[2]+top
		else:
#			s=s+t[2]
#			s='{}{}'.format(s,t[2])
			btm=btm+t[2]

if iturn%2==0:
	s=top+s+btm
else:
	s=btm[::-1]+s[::-1]+top[::-1]
print (s)
### BUGGY CODE ###

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

LR = []
for _ in range(M):
    l, r = map(int, input().split())
    LR.append((l, r))
    
cards = LR[:]
master_ids = set(range(cards[0][0], cards[0][1]+1))
for l, r in cards:
    ids = set(range(l, r+1))
    master_ids = master_ids & ids
    #print(ids, master_ids)
    
ans = len(master_ids)
print(ans)


### FIXED CODE ###

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

LR = []
for _ in range(M):
    l, r = map(int, input().split())
    LR.append((l, r))
    
cards = LR[:]

import sys
INT_MAX = sys.maxsize

left_id = 0
right_id = INT_MAX
for l, r in cards:
    left_id = max(left_id, l)
    right_id = min(right_id, r)
    
if left_id <= right_id:
    ans = right_id + 1 - left_id
else:
    ans = 0
print(ans)
### BUGGY CODE ###

H, W, D = map(int,input().split())
dist = [[float("inf") for i in range(H*W+1)] for j in range(H*W+1)]
for i in range(H*W+1):
  dist[i][i] = 0
#dist[i][j]は隣接行列
pos = [[0,0] for i in range(H*W+1)]
for i in range(H):
  A = list(map(int,input().split()))
  for j in range(W):
    pos[A[j]] = [i+1, j+1]
for i in range(H*W+1-D):
  dist[i][i+D] = abs(pos[i][0]-pos[i+D][0])+abs(pos[i][1]-pos[i+D][1])
for i in range(1,H*W+1-D):
  for j in range(i+1,H*W+1):
    if (j-i)%D==0:
      dist[i][j] = dist[i][j-D]+dist[j-D][j]
Q = int(input())
for i in range(Q):
  L, R = map(int, input().split())
  print(dist[L][R])

### FIXED CODE ###

H, W, D = map(int,input().split())
dist = [0]*(H*W+1)#dist[i]はiからi+Dまでの距離
pos = [[0,0] for i in range(H*W+1)]
for i in range(H):
  A = list(map(int,input().split()))
  for j in range(W):
    pos[A[j]] = [i+1, j+1]
for i in range(H*W+1-D):
  dist[i] = abs(pos[i][0]-pos[i+D][0])+abs(pos[i][1]-pos[i+D][1])
distances = [[] for i in range(D)]#あまりがiの距離
for i in range(1,H*W+1-D):
  d = dist[i]
  distances[i%D]+=[d]
distances2 = [[0] for i in range(D)]#累積和に直す
for i in range(D):
  for j in range(len(distances[i])):
    distances2[i]+=[distances2[i][-1]+distances[i][j]]
Q = int(input())
for i in range(Q):
  L, R = map(int, input().split())
  q = L%D
  l, r = (L-1)//D, (R-1)//D
  print(distances2[q][r]-distances2[q][l])
### BUGGY CODE ###

import sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**20
def I(): return int(input())
def F(): return float(input())
def S(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()

def resolve():
    N, K = LI()
    A = LI()
    F = LI()

    A.sort()

    # 時間tで感触できるか
    def can_complete(t):
        # 食べ物のtに間に合う要求コストを越えてる人のみ修行
        return sum([max(i-j, 0) for i, j in zip(A, sorted([t//i for i in F]))]) <= K

    # for j in range(20):
    #     print(can_complete(j))

    ng = -1
    ok = max(A)*max(F)
    while abs(ok-ng)>1:
        m = (ng+ok)//2
        if can_complete(m):
            ok = m
        else:
            ng = m
    print(ok)

if __name__ == '__main__':
    resolve()


### FIXED CODE ###

import sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**20
def I(): return int(input())
def F(): return float(input())
def S(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()

def resolve():
    N, K = LI()
    A = LI()
    F = LI()

    A.sort()
    F.sort(reverse=True)

    # 時間tで感触できるか
    def can_complete(t):
        return sum([max(i-t//j, 0) for i, j in zip(A, F)]) <= K

    # for j in range(20):
    #     print(can_complete(j))

    ng = -1
    ok = max(A)*max(F)
    while abs(ok-ng)>1:
        m = (ng+ok)//2
        if can_complete(m):
            ok = m
        else:
            ng = m
    print(ok)

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

N=int(input())
S=[input() for i in range(N)]
A=list(set(S))

MAX=0
for i in range(len(A)):
  a=S.count(A[i])
  if a>=MAX:
    MAX=a

ans=[]

for i in A:
  if S.count(i)==MAX:
    ans.append(i)

ans.sort()

for i in range(len(ans)):
  print(ans[i])

### FIXED CODE ###

from collections import Counter

N=int(input())
S=[input() for _ in range(N)]
S=Counter(S)
count=S.most_common()
count.sort(key=lambda x:x[0])
count.sort(key=lambda x:x[1], reverse=True)

n=count[0][1]
for i in range(len(count)):
  if n==count[i][1]:
    print(count[i][0])
  else:
    break