#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<bool> vb;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef map<int,int> mii;
typedef map<ll,ll> mll;
typedef vector<pii> vii;
typedef vector<pll> vll;
#define fi first
#define se second
#define pi 3.141592653589793
#define mod 998244353
#define pb push_back
#define all(v) v.begin(),v.end()
#define tc int t;cin>>t;while(t--)
#define pqmax priority_queue<int>
#define pqmin priority_queue<int,vi,greater<int>>
#define fast_io ios_base::sync_with_stdio(0), cin.tie(NULL)
#define tc_g int tt;cin>>tt;for(int ti=1;ti<=tt;ti++)
#define case_g "Case #"<<ti<<": "
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
typedef tree<int, int, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_map;

class segtree {
public:
	int t[2000];
	
	void build(int v, int tl, int tr) {
        if (tl == tr)
            t[v] = 1;
        else {
            int tm = (tl + tr) / 2;
            build(v*2, tl, tm);
            build(v*2+1, tm+1, tr);
            t[v] = t[v*2] + t[v*2+1];
        }
    }
    
    void leave(int v, int tl, int tr, int pos) {
        t[v]--;
        if (tl != tr) {
            int tm = (tl + tr) / 2;
            if (pos <= tm)
                leave(v*2, tl, tm, pos);
            else
                leave(v*2+1, tm+1, tr, pos);
        }
    }
    
    int sum(int v, int tl, int tr, int l, int r) {
        if (l > r) 
            return 0;
        if (l == tl && r == tr)
            return t[v];
        int tm = (tl + tr) / 2;
        return sum(v*2, tl, tm, l, min(r, tm)) + sum(v*2+1, tm+1, tr, max(l, tm+1), r);
    }
};

int main() {
	fast_io;
	int n;
	cin >> n;
	segtree row[n], col[n];
	for (int i = 0;i < n;i++) {
		row[i].build(1, 0, n - 1);
		col[i].build(1, 0, n - 1);
	}
	int ans = 0;
	for (int i = 0, p;i < n * n;i++) {
		cin >> p;
		int r = (p - 1) / n;
		int c = (p - 1) % n;
		int cost = INT32_MAX;
		cost = min(cost, row[r].sum(1, 0, n - 1, 0, c - 1));
		cost = min(cost, row[r].sum(1, 0, n - 1, c + 1, n - 1));
		cost = min(cost, col[c].sum(1, 0, n - 1, 0, r - 1));
		cost = min(cost, col[c].sum(1, 0, n - 1, r + 1, n - 1));
		row[r].leave(1, 0, n - 1, c);
		col[c].leave(1, 0, n - 1, r);
		ans += cost;
	}
	cout << ans << '\n';
}
