#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define FOR(i, a, b) for(ll i=(a);i<(b);++i)
#define rep(i, n) FOR(i, 0, n)
#define whole(x) (x).begin(),(x).end()
#define UNIQUE(v) v.erase(unique(v.begin(), v.end()), v.end())
using P = pair<int, int>;
#define debug(var) cerr << "[" << #var << "] " << var << endl
#define chmin(x, y) x = min(x, y)
const ll mod = 1000000007;
const int dx[] = {-1,0,1,0};
const int dy[] = {0,-1,0,1};

template<typename T>
struct BIT {
  int n;
  vector<T> d;
  BIT(int n=0):n(n),d(n+1) {}
  void add(int i, T x=1) {
    for (i++; i <= n; i += i&-i) {
      d[i] += x;
    }
  }
  T sum(int i) {
    T x = 0;
    for (i++; i; i -= i&-i) {
      x += d[i];
    }
    return x;
  }
  T sum(int l, int r) {
    return sum(r-1) - sum(l-1);
  }
};


int main(){
    ll n;
    cin >> n;
    vector<ll> p(n*n);
    
    rep(i, n*n) {
        cin >> p[i];
        p[i]--;
    }
    ll ans = 0;

    vector<BIT<ll>> bitx(n, BIT<ll>(n));
    vector<BIT<ll>> bity(n, BIT<ll>(n));
    rep(i, n) {
        rep(j, n) {
            bitx[i].add(j);
            bity[i].add(j);
        }
    }    
    
    rep(i, n*n) {
        ll x = p[i]/n;
        ll y = p[i]%n;
        
        ll v1 = bity[x].sum(y-1);
        if (y==0) v1 = 0;
        ll v2 = bity[x].sum(n-1) - v1 - 1;
        if (y==n-1) v2 = 0;
        ll v3 = bitx[y].sum(x-1);
        if (x==0) v3 = 0;
        ll v4 = bitx[y].sum(n-1) - v3 - 1;
        if (x==n-1) v4 = 0;
        
        ll res = min({v1, v2, v3, v4});
        res = max(res, 0);
        ans += res;
        bitx[y].add(x, -1);
        bity[x].add(y, -1);
    }
    

    
    
    cout << ans << endl;
    

    return 0;
}
