#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
INF = float("inf")


class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i


def main():
    N = int(input())
    P = list(map(lambda x: int(x)-1, input().split()))

    bit = Bit(N)
    for i in range(1, N+1):
        bit.add(i, 1)

    rows = [Bit(N) for i in range(N)]
    cols = [Bit(N) for i in range(N)]
    for r in rows:
        r.tree = bit.tree.copy()
    for c in cols:
        c.tree = bit.tree.copy()

    ans = 0
    for p in P:
        # pの行番号、列番号
        r, c = divmod(p, N)
        # rowで抜ける場合
        t1 = rows[r].sum(c+1)          # 1-index
        t2 = rows[r].sum(N) - rows[r].sum(c)
        # colで抜ける場合
        t3 = cols[c].sum(r+1)          # 1-index
        t4 = cols[c].sum(N) - cols[c].sum(r)
        tt = min(t1, t2, t3, t4)
        ans += tt-1
        rows[r].add(c+1, -1)
        cols[c].add(r+1, -1)
    print(ans)
    return


if __name__ == '__main__':
    main()
