#include <bits/stdc++.h>
using namespace std;
// #include <atcoder/all>
// using namespace atcoder;

typedef long long ll;
typedef pair<ll,ll> P;
typedef pair<P,ll> PLL;
typedef pair<P,P> PP;
typedef vector<ll> llVEC;
typedef vector<P> PVEC;
typedef priority_queue<P,PVEC,greater<P> > PPQ;
typedef priority_queue<ll, llVEC, greater<ll> > llPQ;

#define rep(i,a,n) for(ll i = a;i < n;i++)
#define rrep(i,a,n) for(ll i = n-1; i >= a;i--)
#define LINF (ll)1e18
#define INF (int)1e9
#define fs first
#define sc second

template<typename T>
ll sz(vector<T> &vec){ return (ll)vec.size(); }
template<typename T>
ll sz(priority_queue<T, vector<T>> &pq) {return (ll)pq.size(); }
template<typename T>
ll sz(priority_queue<T, vector<T>, greater<T>> &pq) {return (ll)pq.size(); }
ll sz(string &s) {return (ll)s.size(); } 
ll gcd(ll a,ll b){ return ((!b) ?a :gcd(b, a%b)); }
ll lcm(ll a,ll b){ return a / gcd(a,b) * b; }
bool checkindex(ll i,ll n){ return (i < n && i >= 0); }

#define SEG_LEN (1 << 9)

ll seg[2][500][SEG_LEN*2];

void add(ll ind1, ll ind2,ll ind,ll v){
    ind += SEG_LEN;
    seg[ind1][ind2][ind] += v;
    while(1){
        ind /= 2;
        if(ind <= 0) break;
        seg[ind1][ind2][ind] = seg[ind1][ind2][ind*2] + seg[ind1][ind2][ind*2+1];
    }
    return;
}

ll sum(ll ind1, ll ind2,ll l, ll r){
    l += SEG_LEN; r += SEG_LEN;
    ll res = 0;
    while(l < r){
        if(l % 2 == 1){
            res += seg[ind1][ind2][l];
            l++;
        }
        l /= 2;
        
        if(r % 2 == 1){
            res += seg[ind1][ind2][r-1];
            r--;
        }
        r /= 2;
    }
    return res;
}


int main(){
    ll n;
    cin >> n;
    ll memox[n*n+1] = {};
    ll memoy[n*n+1] = {};
    rep(i,1,n+1){
        rep(j,1,n+1){
            memox[n*(i-1)+j] = i;
            memoy[n*(i-1)+j] = j;
        }
    }

    rep(i,0,n){
        rep(j,0,n){
            add(0,j+1,i+1,1);
            add(1,i+1,j+1,1);
        }
    }

    ll ans = 0,a;
    rep(i,0,n*n){
        cin >> a;  
        add(0,memoy[a],memox[a],-1);
        add(1,memox[a],memoy[a],-1);

        ll temp1 = sum(0,memoy[a],0,memox[a]);
        ll temp2 = sum(0,memoy[a],memox[a]+1,n+2);
        ll temp3 = sum(1,memox[a],0,memoy[a]);
        ll temp4 = sum(1,memox[a],memoy[a]+1,n+2);
        ans += min(min(temp1,temp2),min(temp3,temp4));
    }
    cout << ans << endl;

    return 0;
}

