#define PROBLEM "https://yukicoder.me/problems/no/1028" #include // clang-format off using Int = long long; #define REP_(i, a_, b_, a, b, ...) for (Int i = (a), lim##i = (b); i < lim##i; i++) #define REP(i, ...) REP_(i, __VA_ARGS__, __VA_ARGS__, 0, __VA_ARGS__) struct SetupIO { SetupIO() { std::cin.tie(nullptr), std::ios::sync_with_stdio(false), std::cout << std::fixed << std::setprecision(13); } } setup_io; #ifndef _MY_DEBUG #define dump(...) #endif // clang-format on /** * author: knshnb * created: Sat Apr 18 15:55:11 JST 2020 **/ #define CALL_FROM_TEST // #include "../../src/" #undef CALL_FROM_TEST template T make_vec(S x) { return x; } template auto make_vec(size_t n, Ts... ts) { return std::vector(ts...))>(n, make_vec(ts...)); } signed main() { Int n; std::cin >> n; auto js = make_vec(n, n, -1); REP(i, n) REP(j, n) { Int x; std::cin >> x; js[x - 1][i] = j; } Int ans = 0; REP(idx, n) { auto f = [&](Int mid) { Int ret = 0; REP(i, n) { ret += std::max(std::abs(mid - i), js[idx][i]); } return ret; }; Int l = 0, r = n; while (abs(l - r) > 2) { Int m1 = (2 * l + r) / 3; Int m2 = (l + 2 * r) / 3; if (f(m1) < f(m2)) r = m2; else l = m1; } if (l + 1 < r && f(l + 1) < f(l)) l = l + 1; ans += f(l); } std::cout << ans << std::endl; }