#include <bits/stdc++.h>
using namespace std;
int seg1[555][555 * 4], seg2[555][555 * 4], start = 1;
long long int ans = 0;
int getn1(int y, int l, int r) {
  l += start;
  r += start;
  int vv = 0;
  while (l <= r) {
    if (l % 2) {
      vv += seg1[y][l];
      l++;
    }
    if ((r % 2) == 0) {
      vv += seg1[y][r];
      r--;
    }
    l /= 2;
    r /= 2;
  }
  return vv;
}
int getn2(int x, int l, int r) {
  l += start;
  r += start;
  int vv = 0;
  while (l <= r) {
    if (l % 2) {
      vv += seg2[x][l];
      l++;
    }
    if ((r % 2) == 0) {
      vv += seg2[x][r];
      r--;
    }
    l /= 2;
    r /= 2;
  }
  return vv;
}
void upd1(int y, int wh) {
  wh += start;
  seg1[y][wh] = 0;
  for (int p = wh / 2; p >= 1; p /= 2)
    seg1[y][p] = seg1[y][p * 2] + seg1[y][p * 2 + 1];
}
void upd2(int x, int wh) {
  wh += start;
  seg2[x][wh] = 0;
  for (int p = wh / 2; p >= 1; p /= 2)
    seg2[x][p] = seg2[x][p * 2] + seg2[x][p * 2 + 1];
}
int main(void) {
  int n;
  scanf("%d", &n);
  while (start < n) start *= 2;
  for (int e = 0; e < n; e++) {
    for (int p = start; p < start + n; p++) seg1[e][p] = 1;
    for (int p = start - 1; p >= 1; p--)
      seg1[e][p] = seg1[e][p * 2] + seg1[e][p * 2 + 1];
  }
  for (int e = 0; e < n; e++) {
    for (int p = start; p < start + n; p++) seg2[e][p] = 1;
    for (int p = start - 1; p >= 1; p--)
      seg2[e][p] = seg2[e][p * 2] + seg2[e][p * 2 + 1];
  }
  for (int e = 0; e < n * n; e++) {
    int r;
    scanf("%d", &r);
    r--;
    int yy = r / n;
    int xx = r % n;
    int l1 = getn1(yy, 0, xx - 1);
    l1 = min(l1, getn1(yy, xx + 1, n - 1));
    l1 = min(l1, getn2(xx, 0, yy - 1));
    l1 = min(l1, getn2(xx, yy + 1, n - 1));
    ans += (long long int)l1;
    upd1(yy, xx);
    upd2(xx, yy);
  }
  printf("%lld\n", ans);
  return 0;
}
