#include #define REP(i, m, n) for(int i = (int)(m); i < (int)(n); ++i) #define rep(i, n) REP(i, 0, n) using namespace std; using ll = long long; using ld = long double; template inline bool chmax(T &a, const U &b) { if(a < b) { a = b; return true; } return false; } template inline bool chmin(T &a, const U &b) { if(a > b) { a = b; return true; } return false; } using pint = pair; int n, a[1000][1000]; int main() { cin.tie(0); ios::sync_with_stdio(false); cin >> n; vector> pos(n); rep(i, n) rep(j, n) cin >> a[i][j], a[i][j]--; rep(i, n) { rep(j, n) { pos[a[i][j]].push_back({i, j}); } } ll ans = 0; rep(i, n) { vector cd(n+1, 0), cu(n+1, 0); rep(j, n) { int l = max(0, pos[i][j].first-pos[i][j].second); int r = min(n-1, pos[i][j].first+pos[i][j].second); cd[r+1]++; cu[l]++; } vector down(n+1, 0), up(n+1, 0); rep(j, n) { cd[j+1] += cd[j]; down[j+1] += down[j]+cd[j+1]; } for(int j = n-1; j >= 0; j--) { cu[j] += cu[j+1]; up[j] += up[j+1]+cu[j+1]; } vector s(n); rep(j, n) s[j] = down[j]+up[j]; ll d = (1LL<<60); rep(j, n) { chmin(d, s[j]); } rep(j, n) d += pos[i][j].second; ans += d; } cout << ans << '\n'; return 0; }