#include <bits/stdc++.h>
using namespace std;
using ll = int64_t;
using ii = pair<ll, ll>;
const int N = 505;
struct fenwick {
  int n;
  ll ft[N];
  void update(int k, ll delta) {
    for (++k; k < N; k += (k & (-k))) {
      ft[k] = (ft[k] + delta);
    }
  }
  ll sum(int k) {
    ll ans = 0;
    for (++k; k; k -= (k & (-k))) {
      ans = (ans + ft[k]);
    }
    return ans;
  }
  ll query(int l, int r) {
    if (l == 0) return sum(r);
    return sum(r) - sum(l - 1);
  }
};
int n;
fenwick row[505];
fenwick col[505];
int main() {
  ll ans = 0;
  cin >> n;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      row[i].update(j, 1);
      col[j].update(i, 1);
    }
  }
  for (int _ = 0; _ < n * n; _++) {
    int p;
    cin >> p;
    p--;
    int i = p % n;
    int j = p / n;
    row[i].update(j, -1);
    col[j].update(i, -1);
    ll curr = min({
        row[i].query(0, j),
        row[i].query(j, n),
        col[j].query(i, n),
        col[j].query(0, i),
    });
    ans += curr;
  }
  cout << ans << '\n';
  return 0;
}
