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

# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
buff_readline = sys.stdin.buffer.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def slv(N, P):
    P = [p-1 for p in P]
    cost = [1] * N**2
    occupy = [1] * N**2
    for i in range(N):
        for j in range(N):
            cost[i*N+j] = min(i, j, N-i-1, N-j-1)

    # print('--- init')
    # for i in range(N):
    #     print([cost[i*N+j] for j in range(N)])

    ans = 0
    for p in P:
        ans += cost[p]
        occupy[p] = 0
        i = p // N
        j = p % N
        s = [(i, j)]
        while s:
            x, y = s.pop()
            pi = x*N + y
            for i, j in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]:
                if 0 <= i < N and 0 <= j < N:
                    ni = i*N + j
                    nc = cost[pi] + occupy[pi]
                    if nc < cost[ni]:
                        s.append((i, j))
                        cost[ni] = nc

    return ans


def main():
    N = read_int()
    P = read_int_n()
    print(slv(N, P))

    # N = 500
    # P = list(range(1, N**2+1))
    # random.shuffle(P)
    # print(slv(N, P))


if __name__ == '__main__':
    main()


### FIXED CODE ###

# -*- coding: utf-8 -*-
import sys
buff_readline = sys.stdin.buffer.readline


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def slv(N, P):
    M = N+2
    cost = [0] * M**2
    occupy = [1] * M**2
    for i in range(N):
        im = i*M + M + 1
        for j in range(N):
            cost[im+j] = min(i, j, N-i-1, N-j-1)

    ds = [-1, 1, -M, M]
    ans = 0
    for p in P:
        p -= 1
        x = p // N
        y = p % N
        p = x * M + y + M + 1
        ans += cost[p]
        occupy[p] = 0
        s = []
        s.append(p)
        while s:
            pi = s.pop()
            for d in ds:
                ni = pi + d
                nc = cost[pi] + occupy[pi]
                if nc < cost[ni]:
                    cost[ni] = nc
                    s.append(ni)
    return ans


def main():
    N = read_int()
    P = read_int_n()
    print(slv(N, P))


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

n,m=map(int, input().split())
ab=[]
for _ in range(n):
    tmpa, tmpb=map(int, input().split())
    ab.append((tmpa,tmpb))
ans=0
for d in range(m-1, -1, -1):
    candidate=[i for i in ab if i[0]<=(m-d)]
    if candidate!=[]:
        get=max(list(i[1] for i in candidate))
        work=[t for t in candidate if t[1]==get] 
        ab.remove(work[0])
        ans+=get
print(ans)

### FIXED CODE ###

n,m=map(int, input().split())
ab=[]
for _ in range(n):
    tmpa, tmpb=map(int, input().split())
    ab.append((tmpa,tmpb))
ab.sort(reverse=True)
import heapq
h = []
ans = 0
for i in range(1, m+1):
    while ab and ab[-1][0] == i:
        heapq.heappush(h,ab.pop()[1]*(-1))
    if h:
        ans -= heapq.heappop(h)
print(ans)
### BUGGY CODE ###

import sys
input = sys.stdin.readline

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

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

#print(graph)
v = [0]*N
for i in range(Q):
    p,x = map(int,input().split())
    v[p-1] += x

notv = [True]*N
notv[0] = False
stack = [0]

while stack:
    now = stack.pop(0)
    for i in graph[now]:
        if notv[i]:
            notv[i] = False
            stack.append(i)
            v[i] += v[now]

print(*v)

### FIXED CODE ###

import sys
input = sys.stdin.readline

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

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

#print(graph)
v = [0]*N
for i in range(Q):
    p,x = map(int,input().split())
    v[p-1] += x

notv = [True]*N
notv[0] = False
stack = [0]

while stack:
    now = stack.pop()
    for i in graph[now]:
        if notv[i]:
            notv[i] = False
            stack.append(i)
            v[i] += v[now]

print(*v)
### BUGGY CODE ###

import math

def is_prime(num):
    i = 2
    while i < math.sqrt(num):
        if num % i == 0:
            return False
    return True

N = int(input())
cnt = 0
for i in range(0, N):
    n = int(input())
    if (is_prime(n)):
        cnt = cnt + 1
        
        
print(cnt)

### FIXED CODE ###

def is_prime(num):
    i = 2
    while i*i <= num:
        if num % i == 0:
            return False
        i = i + 1
    return True

N = int(input())
cnt = 0
for i in range(0, N):
    n = int(input())
    if (is_prime(n)):
        cnt = cnt + 1
        
print(cnt)
### BUGGY CODE ###

import bisect
 
N=int(input())
L=list(map(int,input().split()))
 
count=0
L.sort()
for i in range(0,N-1):
  for j in range(i+1,N):
    index=bisect.bisect_left(L[j+1:],L[i]+L[j])
    count+=index
print(count)

### FIXED CODE ###

import bisect
 
N=int(input())
L=list(map(int,input().split()))
 
L.sort()
count=0
for i in range(N):
  for j in range(i+1,N):
    c=L[i]+L[j]
    index=bisect.bisect_left(L,c)
    count+=max(0,index-j-1)
print(count)
### BUGGY CODE ###

import math

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

def is_prime(n):
    if n == 1: return False

    for k in range(2, int(math.sqrt(n)) + 1):
        if n % k == 0:
            return False

    return True

cf = []
for i in range(2,max(A,B)+1):
    if A % i == 0 and B % i == 0:
        cf.append(i)

res = 1
for c in cf:
    if is_prime(c):
        res += 1

print(res)

### FIXED CODE ###

import math

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

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

A_prime = set(prime_factorize(A))
B_prime = set(prime_factorize(B))

res = A_prime & B_prime

print(len(res)+1)
### BUGGY CODE ###

N,M = [int(i) for i in input().split(' ')]
itemList = [int(i) for i in input().split(' ')]
itemList.sort(reverse=True)

for _ in range(M):
    itemList[0] //= 2        
    for i in range(1,N):
        if itemList[0] > itemList[i]:
            item = itemList.pop(0)
            itemList.insert(i-1,item)
            break
        if i == N-1:
            item = itemList.pop(0)
            itemList.append(item)
print(sum(itemList))

### FIXED CODE ###

from heapq import heappush, heappop
import math

N,M = [int(i) for i in input().split(' ')]
itemList = [int(i) for i in input().split(' ')]
heap = []

for i in itemList:
    heappush(heap, -i)

for _ in range(M):
    heappush(heap, math.ceil(heappop(heap)/2))
print(-sum(heap))
### BUGGY CODE ###

n,k=map(int,input().split())
p=list(map(int,input().split()))
d=[]
d2=[]
ans=0
h=0
for i in range(n):
  d.append((1+p[i])/2)
for i in range(n-k+1):
  if h<sum(d[i:i+k]):
    h=sum(d[i:i+k])
print(h)

### FIXED CODE ###

from itertools import accumulate
N, K = list(map(int, input().split()))
C = list(map(int, input().split()))
A=[]
for i in range(N):
  A.append((C[i]+1)/2)
B = [0] + A
B = list(accumulate(B))

ans = []
for i in range(N-K+1):
    ans.append(B[i+K]-B[i])
print(max(ans))
### BUGGY CODE ###

r,g,b,n = map(int,input().split())
counter = 0
a = (n // r)+1
c = (n// g)+1

for i in range(a):
    for j in range(c):
        left = n - (r*i) - (g*j)
        if left >= 0 and   left % b == 0:
            counter += 1
            
print(counter)

### FIXED CODE ###

r,g,b,n = map(int,input().split())
counter = 0
sorts = sorted([r,g,b],reverse=True)
a = (n // sorts[0])+1

for i in range(a):
    test = n
    test = test-(sorts[0]*i)
    c = (test//sorts[1])+1
    for j in range(c):
        left = test - (sorts[1]*j)
        if left >= 0 and   left % sorts[2] == 0:
            counter += 1
            
print(counter)
### BUGGY CODE ###

from collections import deque

h, w = map(int, input().split())
s = [list(map(str, input().rstrip())) for _ in range(h)]


moves = ((1, 0), (-1, 0), (0, 1), (0, -1))
visited = [[False] * w for _ in range(h)]

ans = 0

for i in range(h):
    for j in range(w):
        if visited[i][j]:
            ans += visited[j][j]
            continue
        if s[i][j] == "#":
            grid = [[0] * w for _ in range(h)]
            q = deque([(i, j)])
            grid[i][j] = 1
            while q:
                curr = q.popleft()
                cx, cy = curr[0], curr[1]
                for (mx, my) in moves:
                    if 0 <= cx + mx < h and 0 <= cy + my < w and grid[cx + mx][cy + my] == 0:
                        if s[cx][cy] != s[cx + mx][cy + my]:
                            q.append((cx + mx, cy + my))
                            if s[cx + mx][cy + my] == ".":
                                grid[cx + mx][cy + my] = 2
            grid = sum(grid, [])
            add = grid.count(2)
            ans += add
            visited[i][j] = add
            continue

print(ans)

### FIXED CODE ###

from collections import deque

h, w = map(int, input().split())
grid = [input() for _ in range(h)]
visited = [[0]*w for _ in range(h)]
moves = ((1, 0), (-1, 0), (0, 1), (0, -1))

ans = 0
for i in range(h):
    for j in range(w):
        if not visited[i][j]:
            bcnt, wcnt = 0, 0
            q = deque([(i, j)])
            while q:
                cx, cy = q.popleft()
                if visited[cx][cy]:
                    continue
                if grid[cx][cy] == "#":
                    bcnt += 1
                else:
                    wcnt += 1
                visited[cx][cy] = 1
                for (dx, dy) in moves:
                    if 0 <= cx + dx < h and 0 <= cy + dy < w and not visited[cx + dx][cy + dy] and grid[cx + dx][cy + dy] != grid[cx][cy]:
                        q.append((cx + dx, cy + dy))
            ans += bcnt * wcnt
print(ans)
### BUGGY CODE ###

import math
 
n,p=map(int,input().split())
 
def C(N,P):
    if N == 1: return P
    
    a=math.ceil((P**(1/N)))+2
 
    res=1
    for i in range(2,a):
        if P % i**N == 0 : res = i
 
    return res
 
print(C(n,p))

### FIXED CODE ###

n,p = list(map(int,input().split())) 
i = a = o = 1
m = round(p**(1/n))
for i in range(m,0,-1):
    a = i**n
    if p%a==0:
        print(i)
        exit()
### BUGGY CODE ###

# C 
import numpy as np

# n = 127
n = int(input())

max_n = 100000
memo = np.full(max_n,999999,dtype=np.int64)
memo[0] = 0

nl = [1]
nl6 = nl+[6**i for i in range(1,1000) if 6**i <= 100000]
nl9 = nl+[9**i for i in range(1,1000) if 9**i <= 100000]
nl.sort(reverse=True)


for i in range(1,n+1):
    memo[i] = memo[i-1]+1
    for i6 in nl6:
        if(i-i6 >= 0):
            memo[i] = min(memo[i], memo[i-i6]+1)
        
    for i9 in nl9:
        if(i-i9 >= 0):
            memo[i] = min(memo[i], memo[i-i9]+1)
            
print(memo[n])

### FIXED CODE ###

# C 
# import numpy as np

# n = 127
n = int(input())

max_n = 100000
# memo = np.full(max_n,999999,dtype=np.int32)
memo = [999999]*(max_n+1)
memo[0] = 0

# nl6 = [1, 6, 36, 216, 1296, 7776, 46656]
# nl9 = [1, 9, 81, 729, 6561, 59049]


for i in range(1,n+1):
    memo[i] = memo[i-1]+1
    k = 6
    while i-k >= 0:
        memo[i] = min(memo[i], memo[i-k]+1)
        k *= 6
    k = 9
    while i-k >= 0:
        memo[i] = min(memo[i], memo[i-k]+1)
        k *= 9
        
print(memo[n])
### BUGGY CODE ###

# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

R,C,K=map(int,input().split())
V=[[0]*C for _ in range(R)]
for i in range(K):
    r,c,v=map(int,input().split())
    r-=1
    c-=1
    V[r][c]=v
dp=[[[0]*4 for _ in range(C)] for _ in range(R)]
for y in range(R):
    for x in range(C):
        for i in range(2,-1,-1):
            dp[y][x][i+1]=max(dp[y][x][i+1],dp[y][x][i]+V[y][x])
        if x<C-1:
            for i in range(3,-1,-1):
                dp[y][x+1][i]=max(dp[y][x+1][i],dp[y][x][i])
    if y+1<R:
        for x in range(C):
            dp[y+1][x][0]=max(dp[y][x])
print(max(dp[-1][-1]))

### FIXED CODE ###

# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

R,C,K=map(int,input().split())
V=[[0]*C for _ in range(R)]
for i in range(K):
    r,c,v=map(int,input().split())
    r-=1
    c-=1
    V[r][c]=v
dp=[[0]*4 for _ in range(C)]
prev_dp=[[0]*4 for _ in range(C)]
for y in range(R):
    for x in range(C):
        for i in range(2,-1,-1):
            dp[x][i+1]=max(dp[x][i+1],dp[x][i]+V[y][x])
        if x<C-1:
            for i in range(3,-1,-1):
                dp[x+1][i]=max(dp[x+1][i],dp[x][i])
    if y+1<R:
        prev_dp=dp
        dp=[[0]*4 for _ in range(C)]
        for x in range(C):
            dp[x][0]=max(prev_dp[x])
print(max(dp[-1]))
### BUGGY CODE ###

n=int(input())
a=list(map(int,input().split()))
ans=[]
for i in range(1,n+1):
    ans.append(a.count(i))
for k in ans:
    print(k)



### FIXED CODE ###

n=int(input())
a=list(map(int,input().split()))
ans=[0]*n
for i in a:
    ans[i-1]+=1
for k in ans:
    print(k)
### BUGGY CODE ###

s = input()

ans = 0
for i in range(len(s)):
    if (s[i] == "A"):
        for j in range (len(s) - i - 1):
            if (s[-(j+1)] == "Z" and ans < (j + 1)):
                ans = len(s)-j-i

print(ans)

### FIXED CODE ###

s = input()

ans_a = s.index("A")
ans_z = s.rfind("Z")

print(ans_z - ans_a + 1)
### BUGGY CODE ###

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

      
if n%2==0:
    for i in range(1,n,2):
        if a.count(i) != 2:
            print(0)
            break
    else:
        print(2**(n//2) % (10**9+7))

if n%2==1:
    if a.count(0)!=1:
            print(0)
            exit()        
    for i in range(2,n,2):
        if a.count(i) != 2:
            print(0)
            break
    else:
        print(2**((n-1)//2) % (10**9+7))


### FIXED CODE ###

n=int(input())
a=list(map(int,input().split()))
b=sorted(a)
if n%2==1:
    b=b[1:]

if n%2==0:
    for i in range(n):
        if b[i] != (i//2)*2+1:
            print(0)
            exit()
    else:
        print(2**(n//2) % (10**9+7))

if n%2==1:
    for i in range(n-1):
        if b[i] != (i//2)*2+2:
            print(0)
            exit()
    else:
        print(2**(n//2) % (10**9+7))
### BUGGY CODE ###


import itertools

def main():
    
    input_lines_n = input()
    n = int(input_lines_n)
    
    for i in range(1, n+1):
        ans = 0
        cnt = 0
        for x, y, z in itertools.product(range(n), range(n), range(n)):
            if x > 0 and y > 0 and z > 0:
                ans = x**2 + y**2 + z**2 + x*y + y*z + z*x
                if ans == i:
                    cnt = cnt + 1
        
        print(cnt)
                    
    
if __name__ == "__main__":
    main()


### FIXED CODE ###


import itertools

def main():
    
    input_lines_n = input()
    n = int(input_lines_n)
    xyz_max = 100
    l = [0] * 10001
    
    for x, y, z in itertools.product(range(xyz_max), range(xyz_max), range(xyz_max)):
        fn = 0
        if x > 0 and y > 0 and z > 0:
            fn = x**2 + y**2 + z**2 + x*y + y*z + z*x
            if fn <= n:
                l[fn] += 1
    
    for i in range(1, n+1):
        print(l[i])
                    
    
if __name__ == "__main__":
    main()
### BUGGY CODE ###

# H,W = 3,3
# s = [".#.", "..#", "#.."]

from collections import deque
H,W = map(int, input().split())
s = [input() for _ in range(H)]

ans = 0
kaburi = 0
for i in range(H):
    for j in range(W):
        if s[i][j]==".": continue
        stk = deque([(i,j)]) # stktack
        visited = set([(i,j)])
        while stk: # なくなるまで
            y,x = stk.popleft()

            for dy,dx in ([1,0],[0,1],[-1,0],[0,-1]):
                if 0 <= y+dy < H and 0 <= x+dx < W:
                    if ((s[y][x]=="." and s[y+dy][x+dx] == "#")
                     or (s[y][x]=="#" and s[y+dy][x+dx] == ".") ):
                        if (y+dy,x+dx) in visited: continue
                        stk.append([y+dy,x+dx])
                        visited.add((y+dy,x+dx))
                        # print(i,j, y+dy,x+dx, ans)
                        if s[y+dy][x+dx]=="#": kaburi += 1
                        ans += 1
print(ans-kaburi)

### FIXED CODE ###

class UnionFind:
    """
    - sizeを指定
    - 要素をグループにまとめる(unite) 
    - 要素同士が同じグループか判定する(isSame)
    - 分離はできない
    - par: 親の番号(はじめ par[i]==i つまりすべての頂点が根)
    - 始め各要素は別々のグループ"""
    def __init__(self, size: int):
        self.par = [-1]*size
        for i in range(size):
            self.par[i] = i 
    
    def root(self, x: int) -> int:
        """根を求める"""
        if self.par[x] == x: # if root
            return x
        else:
            self.par[x] = self.root(self.par[x]) # 経路圧縮
            return self.par[x]
    
    def isSame(self, x:int, y:int)->bool:
        """x と y が同じ集合に属するか否か"""
        return self.root(x)==self.root(y)
    
    def unite(self, x:int, y:int):
        """x と y の属する集合を併合"""
        x = self.root(x)
        y = self.root(y)
        if x == y: return
        self.par[x] = y


H,W = map(int, input().split())
s = [input() for _ in range(H)]
uf = UnionFind(H*W) 

def pos2int(h,w):
    # 座標->[0 - H*W]
    return h*W + w

for h in range(H):
    for w in range(W):        
        for dh, dw in zip((0, 1), (1, 0)):
            if not(0<=h+dh<H and 0<=w+dw<W):
                continue
            if s[h][w] != s[h+dh][w+dw]: # 同じグループにする
                uf.unite(pos2int(h, w), pos2int(h+dh, w+dw))
                
white = [0] * H*W
black = [0] * H*W
 
for h in range(H):
    for w in range(W):
        n = pos2int(h, w)
        r = uf.root(n)
        # print(n, r)
        if s[h][w] == ".":
            white[r] += 1
        else:
            black[r] += 1
# print(white)
# print(black)
ans = 0
for h in range(H):
    for w in range(W):
        n = pos2int(h, w)
        ans += white[n] * black[n]
print(ans)
### BUGGY CODE ###

n = int(input())
nums = list(map(int,input().split()))
ans = nums[0]
for i in range(1,n):
        ans *= nums[i]
if ans <= 10**18:
    print(ans)
else:
    print(-1)

### FIXED CODE ###

n = int(input())
nums = list(map(int,input().split()))
ans = 1
if 0 in nums:
  print(0)
else:
  for i in range(n):
    ans *= nums[i]
    if ans > 10**18:
      ans = -1
      break
  print(ans)
### BUGGY CODE ###

N=int(input())
A=list(map(int,input().split()))
s=0
for i in range(N-1):
  for j in range(i+1,N):
    if A[i]!=A[j]:
      s=s
    else:
      s+=1
if s!=0:
  print("NO")
else:
  print("YES")

### FIXED CODE ###

N=int(input())
A=map(int,input().split())
n=len(set(A))
if N!=n:
  print("NO")
else:
  print("YES")
### BUGGY CODE ###

n=int(input())
s=[i for i in input()]
flg=True
while flg:
  flg=False
  for i in range(len(s)-1):
    if s[i]==s[i+1]:
      s.pop(i)
      flg=True
      break
print(len(s))  

### FIXED CODE ###

n=int(input())
s=[i for i in input()]
ss=[s[0]] 
for i in s:
  if ss[-1]!=i:
    ss.append(i)
print(len(ss))
### BUGGY CODE ###

s=input()
t=input()
count=0
while 1:
  if s==t:
    print("Yes")
    break
  if count==len(s):
    print("No")
    break
  s=s[1:]+s[0]

### FIXED CODE ###

s=input()
t=input()
count=0
while 1:
  if s==t:
    print("Yes")
    break
  if count==len(s):
    print("No")
    break
  s=s[1:]+s[0]
  count+=1
### BUGGY CODE ###

n = int(input())
s = [sorted(input()) for _ in range(n)]

count = 0
for i in range(len(s)-1):
    for j in range(i+1,len(s)):
        if s[i] == s[j]:
            count += 1
print(count)

### FIXED CODE ###

n = int(input())
s = ["".join(sorted(input())) for _ in range(n)]

dic = {}
ans = 0
for i in s:
    if i in dic:
        ans += dic[i]
        dic[i] += 1
    else:
        dic[i] = 1
print(ans)
### BUGGY CODE ###

N = int(input())
for h in range(1, 3501):
    for n in range(1, 3501):
        tmp = 4*n*h - N*n - N*h
        if tmp > 0:
            if N * h * n % tmp == 0:
                print(h, n, N * h * n // tmp)
                exit()

### FIXED CODE ###

N = int(input())
for h in range(1, 3501):
    for n in range(1, 3501):
        if 4*n*h - N*n - N*h > 0:
            if N * h * n % (4*n*h - N*n - N*h) == 0:
                print(h, n, N * h * n // (4*n*h - N*n - N*h))
                exit()
### BUGGY CODE ###

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

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

A.sort(reverse=True)

for _ in range(M):
    A[0] //= 2
    A.sort(reverse=True)

print(sum(A))

### FIXED CODE ###

from heapq import heappop,heappush

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

H = []

for i in A:
    heappush(H, -i)

for _ in range(M):
    heappush(H, -((-heappop(H)//2)) )

print(-sum(H))
### BUGGY CODE ###

import bisect
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
a.sort()
b.sort()
c.sort()

b_num = [0 for _ in range(len(b))]
for b_i in range(len(b)):
    c_i = bisect.bisect_right(c, b[b_i])
    b_num[b_i] = len(b) - c_i

ans = 0
for a_i in range(len(a)):
    b_i = bisect.bisect_right(b, a[a_i])
    for j in range(b_i, len(b_num)):
        ans += b_num[j]
print(ans)



### FIXED CODE ###

import bisect
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
a.sort()
b.sort()
c.sort()

b_num = [0 for _ in range(n)]
for b_i in range(n):
    c_i = bisect.bisect_right(c, b[b_i])
    b_num[b_i] = n - c_i

for i in range(1, len(b_num)):
    b_num[len(b_num) - 1 - i] += b_num[len(b_num) - i]

ans = 0
for a_i in range(len(a)):
    b_i = bisect.bisect_right(b, a[a_i])
    if b_i >= n:
        continue
    ans += b_num[b_i]
print(ans)
### BUGGY CODE ###

n = int(input())
a = list(map(int,input().split()))
b = []
for i in range(n):
    b.append(a[i])
    b.reverse()
b=[str(i) for i in b]
b = ' '.join(b)
print(b)

### FIXED CODE ###

n = int(input())
a = list(map(int,input().split()))
b = []
i=0
while n-1-i>=0:
    b.append(str(a[n - 1 - i]))
    i += 2
if n%2==0:
    for i in range(0,n,2):
        b.append(str(a[i]))
else:
    for i in range(1,n,2):
        b.append(str(a[i]))
b=' '.join(b)
print(b)
### BUGGY CODE ###

# https://atcoder.jp/contests/abc077/tasks/arc084_a
# C - Snuke Festival

N = int(input().split()[0])
a_list = sorted(list(map(int, input().split())))
b_list = sorted(list(map(int, input().split())))
c_list = sorted(list(map(int, input().split())))

# あらかじめ計算しておく
b2c_dict = {}
for i in range(N):  # 10 ** 5
    b = b_list[i]
    b2c_dict[i] = len([c for c in c_list if c > b])  # 10 ** 5

comb_n = 0

for i in range(N):  # 10 ** 5
    a = a_list[i]
    for j, b in enumerate(b_list):  # 10 ** 5
        if b > a:
            comb_n += b2c_dict[j]

ans = comb_n
print(ans)


### FIXED CODE ###

# https://atcoder.jp/contests/abc077/tasks/arc084_a
# C - Snuke Festival
import bisect

N = int(input().split()[0])
a_list = sorted(list(map(int, input().split())))
b_list = sorted(list(map(int, input().split())))
c_list = sorted(list(map(int, input().split())))

comb_n = 0
comb_n_list = []

# 自分より大きい個数
start_c_index = 0
start_a_index = 0

for i in range(N):  # 10 ** 5
    b = b_list[i]
    a_n = bisect.bisect_left(a_list, b)
    c_n = N - bisect.bisect_right(c_list, b)
    comb_n += a_n * c_n
ans = comb_n
print(ans)
### BUGGY CODE ###

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

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

candidate = []
candidate.extend(A)

for j in range(M):
    b, c = map(int, input().split())
    for j in range(b):
        candidate.append(c)
        
sorted_candidate = sorted(candidate, reverse=True)

print(sum(sorted_candidate[:N]))

### FIXED CODE ###

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

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

BC = []

for j in range(M):
    b, c = map(int, input().split())
    BC.append((b, c))
    
sorted_BC = sorted(BC, reverse=True, key=lambda item: item[1])

candidate = []
count = N
for bc in sorted_BC:
    b = bc[0]
    c = bc[1]
    if count >= 0:
        candidate.extend([c] * b)
        count = count - b
    else:
        break
    
candidate.extend(A)

print(sum(sorted(candidate, reverse=True)[:N]))