#include <bits/stdc++.h>
long long N;
std::vector<std::vector<long long>> rows, cols;
int sum(std::vector<long long>& A, int i) {
  long long sum = 0;
  while (i > 0) sum += A[i], i -= ((i) & -(i));
  return sum;
}
void add(std::vector<long long>& A, int i, long long k) {
  while (i <= N) A[i] += k, i += ((i) & -(i));
}
int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(0);
  std::cin >> N;
  rows.assign(N + 1, std::vector<long long>(N + 1, 0));
  cols.assign(N + 1, std::vector<long long>(N + 1, 0));
  for (int i = 1; i <= N; i++)
    for (int j = 1; j <= N; j++) {
      add(rows[i], j, 1);
      add(cols[i], j, 1);
    }
  long long res = 0;
  for (int i = 0; i < N * N; i++) {
    long long idx;
    std::cin >> idx;
    long long r = ((idx - 1) / N) + 1, c = ((idx - 1) % N) + 1;
    long long prer = sum(rows[r], c - 1), prec = sum(cols[c], r - 1);
    long long postr = sum(rows[r], N) - prer - 1,
              postc = sum(cols[c], N) - prec - 1;
    res += std::min(std::min(prer, postr), std::min(prec, postc));
    add(rows[r], c, -1);
    add(cols[c], r, -1);
  }
  std::cout << res << "\n";
}
