#include <bits/stdc++.h>
using namespace std;
using lli = long long int;
using ii = pair<int, int>;
const int MAXN = 502;
int n;
int bit_row[MAXN][MAXN];
int bit_col[MAXN][MAXN];
int count_row[MAXN];
int count_col[MAXN];
void add_bit(int* bit, int pos, int val) {
  while (pos <= n) {
    bit[pos] += val;
    pos += pos & (-pos);
  }
}
int get_bit(int* bit, int pos) {
  int sum = 0;
  while (pos > 0) {
    sum += bit[pos];
    pos -= pos & (-pos);
  }
  return sum;
}
int main() {
  scanf("%d", &n);
  vector<int> p(n * n);
  for (int i = 0; i < n * n; i++) {
    scanf("%d", &p[i]);
  }
  for (int row = 1; row <= n; row++) {
    count_row[row] = n;
    count_col[row] = n;
    for (int col = 1; col <= n; col++) {
      add_bit(bit_row[row], col, 1);
      add_bit(bit_col[col], row, 1);
    }
  }
  lli ans = 0;
  for (int i = 0; i < n * n; i++) {
    int row = (p[i] - 1) / n + 1;
    int col = ((p[i] - 1) % n) + 1;
    int up = get_bit(bit_col[col], row - 1);
    int down = count_col[col] - up - 1;
    int left = get_bit(bit_row[row], col - 1);
    int right = count_row[row] - left - 1;
    ans += lli(min({up, down, left, right}));
    add_bit(bit_col[col], row, -1);
    add_bit(bit_row[row], col, -1);
    count_row[row]--;
    count_col[col]--;
  }
  printf("%I64d\n", ans);
}
