#include #include #include using namespace std; using ll = int_fast64_t; #define int ll #define rep(i,n) for(int (i) = 0 ; (i) < (n) ; (i)++) #define rng(i,s,n) for(int (i) = (s) ; (i) < (n) ; (i)++) templatebool chmax(T & a, const T & b) { if (a < b) { a = b; return 1; } return 0; } templatebool chmin(T & a, const T & b) { if (b < a) { a = b; return 1; } return 0; } ll read() { ll u, k = scanf("%lld", &u); return u; } int n; int a[2000][2000]; int b[2000];//現在のコスト int ans[2000];//答えのコスト int c[2000][2]; void solve() { cin >> n; rep(i, n)rep(j, n) { a[i][j] = read() - 1; b[a[i][j]] += i + j - min(i, j); if (j < i) c[a[i][j]][1]++; } rep(i, n) { ans[i] = b[i]; } rep(i, n) { for (int j = 0; i - j >= 0; j++) { c[a[i - j][j]][0]++; } rep(j, n) { b[j] += c[j][0] - c[j][1]; } rep(j, n) chmin(ans[j], b[j]); for (int j = 0; i + j + 1 < n; j++) { c[a[i + j + 1][j]][1]--; } } int sum = 0; rep(i, n) sum += ans[i]; cout << sum << endl; } signed main() { solve(); }