//Utkarsh.25dec
#include <bits/stdc++.h>
#include <chrono>
#include <random>
#define ll long long int
#define ull unsigned long long int
#define pb push_back
#define mp make_pair
#define mod 1000000007
#define rep(i,n) for(ll i=0;i<n;i++)
#define loop(i,a,b) for(ll i=a;i<=b;i++)
#define vi vector <int>
#define vs vector <string>
#define vc vector <char>
#define vl vector <ll>
#define all(c) (c).begin(),(c).end()
#define max3(a,b,c) max(max(a,b),c)
#define min3(a,b,c) min(min(a,b),c)
#define deb(x) cerr<<#x<<' '<<'='<<' '<<x<<'\n'
using namespace std;
#include <ext/pb_ds/assoc_container.hpp> 
#include <ext/pb_ds/tree_policy.hpp> 
using namespace __gnu_pbds; 
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
// ordered_set s ; s.order_of_key(val)  no. of elements strictly less than val
// s.find_by_order(i)  itertor to ith element (0 indexed)
typedef vector<vector<ll>> matrix;
ll power(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll modInverse(ll a){return power(a,mod-2);}
const int N=500023;
bool vis[N];
ordered_set row[N],col[N];
ll n;
int getrow(int i)
{
    int ans=(i-1)/n+1;
    return ans;
}
int getcol(int i)
{
    int ans=i%n;
    if(ans==0)
        ans+=n;
    return ans;
}
void solve()
{
    cin>>n;
    vl v;
    v.pb(0);
    for(int i=1;i<=n*n;i++)
    {
        ll c;
        cin>>c;
        v.pb(c);
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=(i-1)*n+1;j<=(i*n);j++)
        {
            row[i].insert(j);
        }
    }
    for(int i=1;i<=n;i++)
    {
        int iter=1;
        for(int j=i;iter<=n;j+=n,iter++)
        {
            col[i].insert(j);
        }
    }
    ll ans=0;
    for(int i=1;i<=n*n;i++)
    {
        ll now=v[i];
        int r=getrow(now);
        int c=getcol(now);
        int left=row[r].order_of_key(now);
        int right=row[r].size()-left-1;
        int up=col[c].order_of_key(now);
        int down=col[c].size()-up-1;
        int add=min3(left,right,up);
        add=min(add,down);
        ans+=add;
        row[r].erase(now);
        col[c].erase(now);
    }
    cout<<ans<<'\n';
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int T=1;
    // cin>>T;
    int t=0;
    while(t++<T)
    {
        //cout<<"Case #"<<t<<":"<<' ';
        solve();
        //cout<<'\n';
    }
    cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC << "ms\n";
}