#include "bits/stdc++.h" #pragma warning(disable:4996) using namespace std; #define int long long #define rep(i,n) for(int i=0;i P; int a[1005][1005]; vector

pos[1005]; signed main() { int n; cin >> n; rep(i, n) { rep(j, n) { cin >> a[i][j]; a[i][j]--; pos[a[i][j]].push_back(P(i, j)); } } int ans = 0; rep(I, n) { vectorimos(n + 1); vectorimos1(n + 1), imos2(n + 1); assert(pos[I].size() == n); rep(j, n) { int x = pos[I][j].first, y = pos[I][j].second; imos1[0]++; imos1[max(x - y,0ll)]--; imos2[min(x + y + 1,n)]++; imos2[n]--; } rep(i, n) { imos1[i + 1] += imos1[i]; imos2[i + 1] += imos2[i]; } for (int i = n; i > 0; i--)imos1[i - 1] += imos1[i]; rep(i, n)imos2[i + 1] += imos2[i]; rep(i, n)imos[i] = imos1[i] + imos2[i]; int pos2, mx = 1e17; rep(i, n) { if (mx > imos[i]) { mx = imos[i]; pos2 = i; } } rep(j, n) { int x = pos[I][j].first, y = pos[I][j].second; ans += max(abs(x - pos2), y); } } cout << ans << endl; }