#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9 + 7;
const long long INF = 1LL << 60;
const long long mod = 1e9 + 7;
const long double eps = 1e-8;
const long double pi = acos(-1.0);
template <class T>
inline bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class T>
inline bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class Abel>
struct BIT {
 private:
  vector<Abel> node;
  int n;
  Abel UNITY_SUM = 0;

 public:
  BIT(int n_) {
    n = n_;
    node.resize(n, UNITY_SUM);
  }
  void init(int n_) {
    n = n_;
    node.resize(n, UNITY_SUM);
  }
  void add(int a, Abel w) {
    for (int i = a; i < n; i |= i + 1) node[i] += w;
  }
  Abel sum(int a) {
    Abel ret = UNITY_SUM;
    for (int i = a - 1; i >= 0; i = (i & (i + 1)) - 1) ret += node[i];
    return ret;
  }
  Abel sum(int a, int b) { return sum(b) - sum(a); }
  int get(int k) {
    ++k;
    int res = 0;
    int n = 1;
    while (n < (int)node.size()) n *= 2;
    for (int i = n / 2; i > 0; i /= 2) {
      if (res + i < (int)node.size() && node[res + i - 1] < k) {
        k -= node[res + i - 1];
        res += i;
      }
    }
    return res;
  }
  void print() {
    for (int i = 0; i < n; ++i) cout << sum(i, i + 1) << ",";
    cout << endl;
  }
};
void solve() {
  int n;
  cin >> n;
  vector<int> p(n * n);
  for (int i = 0; i < n * n; i++) {
    cin >> p[i];
    --p[i];
  }
  reverse(p.begin(), p.end());
  vector<BIT<int>> a(n, BIT<int>(n)), b(n, BIT<int>(n));
  int ans = 0;
  for (int i = 0; i < n * n; i++) {
    int x = p[i] / n, y = p[i] % n;
    ans +=
        min({a[x].sum(0, y), a[x].sum(y, n), b[y].sum(0, x), b[y].sum(x, n)});
    a[x].add(y, 1);
    b[y].add(x, 1);
  }
  cout << ans << endl;
}
signed main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  solve();
  return 0;
}
