#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, int>;
const ll mod = 1000000007;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, -1, 0, 1};
template <typename T>
struct BIT {
  int n;
  vector<T> d;
  BIT(int n = 0) : n(n), d(n + 1) {}
  void add(int i, T x = 1) {
    for (i++; i <= n; i += i & -i) {
      d[i] += x;
    }
  }
  T sum(int i) {
    T x = 0;
    for (i++; i; i -= i & -i) {
      x += d[i];
    }
    return x;
  }
  T sum(int l, int r) { return sum(r - 1) - sum(l - 1); }
};
int main() {
  int n;
  cin >> n;
  vector<ll> p(n * n);
  for (ll i = (0); i < (n * n); ++i) {
    cin >> p[i];
    p[i]--;
  }
  ll ans = 0;
  vector<BIT<ll>> bitx(n, BIT<ll>(n));
  vector<BIT<ll>> bity(n, BIT<ll>(n));
  for (ll i = (0); i < (n * n); ++i) {
    int x = p[i] / n;
    int y = p[i] % n;
    ll v1 = y - bity[x].sum(y - 1);
    ll v2 = n - y - 1 - (bity[x].sum(n - 1) - bity[x].sum(y));
    ll v3 = x - bitx[y].sum(x - 1);
    ll v4 = n - x - 1 - (bitx[y].sum(n - 1) - bitx[y].sum(x));
    ll res = min(min(v1, v2), min(v3, v4));
    res = max(res, 0LL);
    ans += res;
    bitx[y].add(x, 1LL);
    bity[x].add(y, 1LL);
  }
  cout << ans << endl;
  return 0;
}
