#include <bits/stdc++.h>
using namespace std;
template <class A, class B>
ostream& operator<<(ostream& out, const pair<A, B>& a) {
  return out << "(" << a.first << ", " << a.second << ")";
}
template <class A>
ostream& operator<<(ostream& out, const vector<A>& v) {
  out << "[";
  for (int i = 0; i < int(int(v.size())); i++) {
    if (i) out << ", ";
    out << v[i];
  }
  return out << "]";
}
mt19937 rnd(time(NULL));
const int INF = int(1e9);
const long long INF64 = long long(1e18);
const int MOD = int(1e9) + 7;
const long double EPS = 1e-9;
const long double PI = acos(-1.0);
const int N = 500 + 7;
int n;
int a[N * N];
bool read() {
  if (scanf("%d", &n) != 1) return false;
  for (int i = 0; i < int(n * n); i++) {
    scanf("%d", &a[i]);
    --a[i];
  }
  return true;
}
int f[N][N];
void upd(int first, int second, int val) {
  for (int i = first; i < n; i |= i + 1)
    for (int j = second; j < n; j |= j + 1) f[i][j] += val;
}
int get(int first, int second) {
  int sum = 0;
  for (int i = first; i >= 0; i = (i & (i + 1)) - 1)
    for (int j = second; j >= 0; j = (j & (j + 1)) - 1) sum += f[i][j];
  return sum;
}
int get(int x1, int y1, int x2, int y2) {
  return get(x2, y2) - get(x2, y1 - 1) - get(x1 - 1, y2) + get(x1 - 1, y1 - 1);
}
void solve() {
  memset(f, 0, sizeof(f));
  for (int i = 0; i < int(n); i++)
    for (int j = 0; j < int(n); j++) upd(i, j, 1);
  long long ans = 0;
  for (int i = 0; i < int(n * n); i++) {
    int first = a[i] / n;
    int second = a[i] % n;
    ans += min({get(0, second, first, second), get(first, 0, first, second),
                get(first, second, n - 1, second),
                get(first, second, first, n - 1)}) -
           1;
    upd(first, second, -1);
  }
  printf("%lld\n", ans);
}
int main() {
  cerr.precision(15);
  cout.precision(15);
  cerr << fixed;
  cout << fixed;
  if (read()) {
    solve();
  }
}
