#include <bits/stdc++.h>
using namespace std;
const int maxn = 510 * 510;
int n, c[510][510], c2[510][510], a[maxn];
void f(int p, int &x, int &y) {
  if (p % n == 0) {
    x = p / n;
    y = n;
  } else {
    x = p / n + 1;
    y = p % n;
  }
}
int lowbit(int x) { return x & (-x); }
void add(int c[], int x) {
  while (x <= n) {
    c[x] += 1;
    x += lowbit(x);
  }
}
int ask(int c[], int x) {
  int ret;
  ret = 0;
  while (x) {
    ret += c[x];
    x -= lowbit(x);
  }
  return ret;
}
int main() {
  int aa, b, cc, d, x, y, ans;
  scanf("%d", &n);
  for (int i = 1; i <= n * n; i++) {
    scanf("%d", &a[i]);
  }
  for (int i = 1; i <= n * n / 2; i++) {
    swap(a[i], a[n * n - i + 1]);
  }
  ans = 0;
  for (int i = 1; i <= n * n; i++) {
    x = 0;
    y = 0;
    f(a[i], x, y);
    aa = ask(c[x], y - 1);
    b = ask(c[x], n) - ask(c[x], min(y, n));
    cc = ask(c2[y], x - 1);
    d = ask(c2[y], n) - ask(c2[y], min(x, n));
    ans += min(aa, min(b, min(cc, d)));
    add(c[x], y);
    add(c2[y], x);
  }
  printf("%d\n", ans);
  return 0;
}
