#include <bits/stdc++.h>
using namespace std;
template <typename T>
ostream &operator<<(ostream &os, vector<T> &v) {
  string sep = " ";
  if (v.size()) os << v[0];
  for (int i = 1; i < v.size(); i++) os << sep << v[i];
  return os;
}
template <class T>
struct Bit {
  std::vector<T> v;
  int n;
  Bit(int n_) : n(n_) { v.assign(n_, 0); }
  T sum(int i) {
    T s = 0;
    while (i > 0) {
      s += v[i];
      i -= i & -i;
    }
    return s;
  }
  void add(int i, T x) {
    while (i < n) {
      v[i] += x;
      i += i & -i;
    }
  }
};
int crossing(std::vector<int> &v) {
  Bit<int> bit(v.size() + 1);
  int count = 0;
  for (int i = 0; i < v.size(); i++) {
    count += i - bit.sum(v[i]);
    bit.add(v[i], 1);
  }
  return count;
}
int _main() {
  using namespace std;
  Bit<int> bit(10);
  bit.add(1, 10);
  bit.add(5, 20);
  assert(bit.sum(0) == 0);
  assert(bit.sum(2) == 10);
  assert(bit.sum(5) == 30);
  assert(bit.sum(8) == 30);
  vector<int> v = {3, 5, 1, 2, 4};
  assert(crossing(v) == 5);
  return 0;
}
int main() {
  ios_base::sync_with_stdio(false);
  int n;
  cin >> n;
  vector<int> p(n * n);
  for (int i = 0; i < n * n; i++) {
    cin >> p[i];
    p[i]--;
  }
  vector<Bit<int>> xb(n, Bit<int>(n + 1));
  vector<Bit<int>> yb(n, Bit<int>(n + 1));
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      xb[i].add(j + 1, 1);
      yb[j].add(i + 1, 1);
    }
  }
  long long ans = 0;
  for (int i = 0; i < n * n; i++) {
    int x = p[i] % n;
    int y = p[i] / n;
    int mx = xb[x].sum(y);
    int nx = xb[x].sum(n);
    int my = yb[y].sum(x);
    int ny = yb[y].sum(n);
    int z = min(min(mx, nx - mx - 1), min(my, ny - my - 1));
    ;
    ans += z;
    xb[x].add(y + 1, -1);
    yb[y].add(x + 1, -1);
  }
  cout << ans << endl;
  return 0;
}
