#include using namespace std; #define int long long templatebool chmax(T &a, const T &b) { if (abool chmin(T &a, const T &b) { if (b struct cumulative_sum_linear { int n; vector x, a, b; cumulative_sum_linear(int n_ = 0) : n(n_), x(n), a(n + 1), b(n + 1) {} void add(int l, int r, T aa, T bb) { a[l] += aa; a[r] -= aa; a[l] -= bb * l; a[r] += bb * l; b[l] += bb; b[r] -= bb; } void exec() { for (int i = 0; i < n; ++i) { x[i] = a[i] + b[i] * i; a[i + 1] += a[i]; b[i + 1] += b[i]; } } T operator[](int i) const { return x[i]; } }; signed main(){ int n; cin >> n; int a[1010][1010]; for(int i = 0;i < n;i++){ int b[1010]; for(int j = 0;j < n;j++){ cin >> b[j]; a[i][b[j]-1] = j; } } int ans = 0; for(int num = 0;num < n;num++){ cumulative_sum_linear imos(n); for(int i = 0;i < n;i++){ int d = a[i][num]; int l = max(i-d, 0ll); int r = min(i+d, n-1ll); imos.add(0ll, l, i, -1); imos.add(l, r+1, d, 0); imos.add(r+1, n, d+1, 1); } imos.exec(); int mi = LLONG_MAX; for(int i = 0;i < n;i++){ chmin(mi, imos[i]); } ans += mi; } cout << ans << endl; return 0; }