#include #include int main() { int N; std::cin >> N; std::vector> A(N, std::vector(N)); std::vector b(N), res(N); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) { std::cin >> A[i][j]; A[i][j]--; b[A[i][j]] += std::max(i, j); res[A[i][j]] += std::max(i, j); } std::vector> cs1(N, std::vector(N)), cs2(N, std::vector(N)); for (int k = 0; k < N - 1; k++) for (int i = 0; i <= k; i++) { cs1[k][A[i][k - i]]++; cs2[N - 2 - k][A[N - 1 - i][k - i]]++; } for (int k = 1; k < N - 1; k++) for (int i = 0; i < N; i++) { cs1[k][i] += cs1[k - 1][i]; cs2[N - 2 - k][i] += cs2[N - 2 - k + 1][i]; } for (int k = 0; k < N - 1; k++) { for (int i = 0; i < N; i++) b[i] += cs1[k][i] - cs2[k][i]; for (int i = 0; i < N; i++) res[i] = std::min(res[i], b[i]); } int ans = 0; for (int i = 0; i < N; i++) ans += res[i]; std::cout << ans << "\n"; }