#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007;
void update(int* BIT, int idx, int n, int val) {
  while (idx <= n) {
    BIT[idx] += val;
    idx += (idx & -idx);
  }
}
int sum(int* BIT, int idx) {
  int sum = 0;
  while (idx > 0) {
    sum += BIT[idx];
    idx -= (idx & -idx);
  }
  return sum;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  long long n;
  cin >> n;
  long long p[n * n];
  for (int i = 0; i < n * n; i++) {
    cin >> p[i];
    --p[i];
  }
  int* BITrows[n];
  int* BITcols[n];
  for (int i = 0; i < n; i++) {
    BITrows[i] = new int[n + 1];
    BITcols[i] = new int[n + 1];
    for (int j = 0; j <= n; j++) BITrows[i][j] = BITcols[i][j] = 0;
  }
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++) {
      update(BITrows[i], j + 1, n, 1);
      update(BITcols[j], i + 1, n, 1);
    }
  vector<int> rowsz(n, n);
  vector<int> colsz(n, n);
  int ans = 0;
  for (int i = 0; i < n * n; i++) {
    int r = p[i] / n, c = p[i] % n;
    update(BITrows[r], c + 1, n, -1);
    --rowsz[r];
    update(BITcols[c], r + 1, n, -1);
    --colsz[c];
    int rsum = sum(BITrows[r], c);
    int csum = sum(BITcols[c], r);
    ans += min(min(rsum, rowsz[r] - rsum), min(csum, colsz[c] - csum));
  }
  cout << ans << endl;
}
