import math,bisect
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
  
n = int(readline())
a = [int(i) for i in readline().split()]
chk_y = [[0] for i in range(n)]
chk_t = [[0] for i in range(n)]
ans = 0
a = a[::-1]
    
for j in range(n*n):
  c = a[j]
  Y = math.ceil(c/n)
  T = c%n
  bisect.insort(chk_y[Y-1],c)
  bisect.insort(chk_t[T-1],c)
  
  if T > 1 and 1 < Y < n:
    if chk_y[Y-1][1] < c < chk_y[Y-1][-1] and chk_t[T-1][1] < c < chk_t[T-1][-1]:
      g = bisect.bisect_left(chk_y[Y-1],c)
      w = bisect.bisect_left(chk_t[T-1],c)
      ans += min(len(chk_y[Y-1])-g-1,g-1,len(chk_t[T-1])-w-1,w-1)
      #print(c,ans)

print(ans)