#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long LLINF = 1e18;
const int maxN = 505;
long long BIT_ROW[maxN][maxN];
long long BIT_COL[maxN][maxN];
int n;
void updBIT_ROW(int ind, int p, long long val = 1) {
  p++;
  for (; p < maxN; p += p & -p) BIT_ROW[ind][p] += val;
}
long long sumBIT_ROW(int ind, long long p) {
  p++;
  long long ret = 0;
  for (; p; p -= p & -p) ret += BIT_ROW[ind][p];
  return ret;
}
void updBIT_COL(int ind, int p, long long val = 1) {
  p++;
  for (; p < maxN; p += p & -p) BIT_COL[ind][p] += val;
}
long long sumBIT_COL(int ind, long long p) {
  p++;
  long long ret = 0;
  for (; p; p -= p & -p) ret += BIT_COL[ind][p];
  return ret;
}
int get_row(int x) { return x / n; }
int get_col(int x) { return x % n; }
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      updBIT_COL(j, i);
      updBIT_ROW(i, j);
    }
  }
  long long ans = 0;
  for (int i = 0; i < n * n; i++) {
    int aux;
    scanf("%d", &aux);
    aux--;
    int row = get_row(aux);
    int col = get_col(aux);
    updBIT_ROW(row, col, -1);
    updBIT_COL(col, row, -1);
    long long go_l = sumBIT_ROW(row, col);
    long long go_r = sumBIT_ROW(row, n) - sumBIT_ROW(row, col);
    long long go_u = sumBIT_COL(col, row);
    long long go_d = sumBIT_COL(col, n) - sumBIT_COL(col, row);
    printf("%d %d %d\n", aux, row, col);
    printf("\tleft %lld right %lld up %lld down %lld\n", go_l, go_r, go_u,
           go_d);
    ans += min(min(go_l, go_r), min(go_u, go_d));
  }
  printf("%lld\n", ans);
  return 0;
}
