#include <bits/stdc++.h>
using namespace std;
const int N = 509;
int n, m;
struct fen {
  int bit[N * 2];
  int sum(int r) {
    int ret = 0;
    for (++r; r > 0; r -= r & -r) {
      ret += bit[r];
    }
    return ret;
  }
  void add(int i, int d) {
    for (++i; i < m; i += i & -i) {
      bit[i] += d;
    }
  }
};
int p[N * N];
fen cols[N], rows[N];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> n;
  m = 1;
  while (m <= n) {
    m *= 2;
  }
  for (int i = 0; i < n * n; ++i) {
    cin >> p[i];
  }
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
      cols[i].add(j, 1);
      rows[i].add(j, 1);
    }
  }
  int ans = 0;
  for (int i = 0; i < n * n; ++i) {
    int cur = p[i] - 1, x = cur / n, y = cur % n;
    int l = rows[x].sum(y) - 1, r = rows[x].sum(n - 1) - l - 1;
    int u = cols[y].sum(x) - 1, d = cols[y].sum(n - 1) - u - 1;
    ans += min(l, min(r, min(u, d)));
    rows[x].add(y, -1);
    cols[y].add(x, -1);
  }
  cout << ans << endl;
  return 0;
}
