#include <bits/stdc++.h>
using namespace std;
int a[510000], n;
typedef struct {
  int dt[510] = {0};
  int add(int x, int k) {
    int w = x;
    while (w <= n) {
      dt[w] += k;
      w = w + (w & -w);
    }
    return 0;
  }
  int qiu(int x) {
    int w = x, sum = 0;
    while (w >= 1) {
      sum += dt[w];
      w = w - (w & -w);
    }
    return sum;
  }
  void cs() {
    for (int x = 1; x <= n; x++) {
      add(x, 1);
    }
  }
} fhs;
fhs h[510], l[510];
int ans = 0;
int main() {
  cin >> n;
  for (int x = 1; x <= n * n; x++) {
    cin >> a[x];
  }
  for (int x = 1; x <= n; x++) {
    h[x].cs();
    l[x].cs();
  }
  for (int x = 1; x <= n * n; x++) {
    int q1 = (a[x] % n);
    if (q1 == 0) {
      q1 = n;
    }
    int q2 = ((a[x] - 1) / n) + 1;
    ans += min(min(h[q2].qiu(q1) - 1, h[q2].qiu(n) - h[q2].qiu(q1)),
               min(l[q1].qiu(q2) - 1, l[q1].qiu(n) - l[q1].qiu(q2)));
    h[q2].add(q1, -1);
    l[q1].add(q2, -1);
  }
  cout << ans << endl;
}
