#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
using v2 = vector<vector<T>>;
template <typename T>
inline v2<T> fill(int r, int c, T t) {
  return v2<T>(r, vector<T>(c, t));
}
int n, l;
v2<int> sr, sc;
vector<array<int, 2>> r;
int sum(vector<int>& st, int s, int e, int ind) {
  if (s > e) {
    return 0;
  }
  if (ind >= l / 2 || (r[ind][0] == s && r[ind][1] == e)) {
    return st[ind];
  }
  int ans = 0;
  array<int, 2> r1 = r[2 * ind];
  array<int, 2> r2 = r[2 * ind + 1];
  if ((s >= r1[0] && s <= r1[1]) || (e >= r1[0] && e <= r1[1])) {
    ans += sum(st, s, e, 2 * ind);
  }
  if ((s >= r2[0] && s <= r2[1]) || (e >= r2[0] && e <= r2[1])) {
    ans += sum(st, s, e, 2 * ind + 1);
  }
  return ans;
}
void update(vector<int>& st, int ind) {
  ind += l / 2;
  while (ind >= 1) {
    st[ind]--;
    ind /= 2;
  }
}
void solve() {
  cin >> n;
  l = 1 << (33 - __builtin_clz(n - 1));
  sr = fill(n, l, 0);
  sc = fill(n, l, 0);
  r = vector<array<int, 2>>(l);
  for (int i = l / 2; i < l; i++) {
    r[i] = {i - l / 2, i - l / 2};
  }
  for (int i = l / 2 - 1; i > 0; i--) {
    r[i] = {r[2 * i][0], r[2 * i + 1][1]};
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      sr[i][j + l / 2] = 1;
      sc[i][j + l / 2] = 1;
    }
    for (int j = l / 2 - 1; j > 0; j--) {
      sr[i][j] = sr[i][2 * j] + sr[i][2 * j + 1];
      sc[i][j] = sc[i][2 * j] + sc[i][2 * j + 1];
    }
  }
  int ans = 0;
  for (int i = 0; i < n * n; i++) {
    int p;
    cin >> p;
    p--;
    int r = p / n;
    int c = p % n;
    ans += min({
        sum(sr[r], 0, c - 1, 1),
        sum(sr[r], c + 1, n - 1, 1),
        sum(sr[c], 0, r - 1, 1),
        sum(sr[c], r + 1, n - 1, 1),
    });
    update(sr[r], c);
    update(sc[c], r);
  }
  cout << ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  solve();
  return 0;
}
