#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
const long long INF_LL = 1e18 + 3;
const int INF_int = 1e9 + 3;
struct BinaryIndexedTree {
  long data[500000];
  int n;
  BinaryIndexedTree(int nn) {
    for (int i = 0; i < nn; i++) data[i + 1] = 0;
    n = nn;
  }
  long sum(int a) {
    long ret = 0;
    while (a > 0) {
      ret += data[a];
      a -= a & (-a);
    }
    return ret;
  }
  void add(int a, long b) {
    while (a <= n) {
      data[a] += b;
      a += a & (-a);
    }
  }
};
int main() {
  int n;
  cin >> n;
  int arr[n * n];
  for (int i = 0; i < n * n; i++) cin >> arr[i];
  BinaryIndexedTree tmp(n);
  vector<BinaryIndexedTree> amari;
  vector<BinaryIndexedTree> syou;
  for (int i = 0; i < n + 1; i++) amari.push_back(tmp), syou.push_back(tmp);
  long long ans = 0;
  for (int i = 0; i < n * n; i++) {
    int now = arr[i];
    int sy = (now + n - 1) / n;
    int am = (now) % n;
    if (am == 0) am += n;
    int n1 = amari[am].sum(sy);
    int n1_ = (n - sy) - (amari[am].sum(n) - n1);
    n1 = sy - 1 - n1;
    n1 = min(n1, n1_);
    int n2 = syou[sy].sum(am);
    int n2_ = (n - am) - (syou[sy].sum(n) - n2);
    n2 = (am - 1 - n2);
    n2 = min(n2, n2_);
    amari[am].add(sy, 1);
    syou[sy].add(am, 1);
    ans += min(n1, n2);
  }
  cout << ans << endl;
}
