#include #define all(vec) vec.begin(), vec.end() #define pb push_back #define eb emplace_back using namespace std; using ll = long long; using P = pair; template using V = vector; constexpr ll INF = (1LL << 30) - 1LL; constexpr ll MOD = 998244353LL; constexpr int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; template void chmin(T &a, T b) { a = min(a, b); } template void chmax(T &a, T b) { a = max(a, b); } void debug() { cerr << "ok" << endl; } template void vout(const vector &v) { for (int i = 0; i < v.size(); i++) { cout << v[i] << (i + 1 == v.size() ? '\n' : ' '); } } int main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; V> a(n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int aa; cin >> aa; --aa; a[aa].eb(i, j); } } auto calc = [&](int i, int x) { ll sum = 0; for (auto &e : a[i]) { sum += max(abs(e.first - x), e.second); } return sum; }; ll res = 0; for (int i = 0; i < n; i++) { double l = 0, r = n - 1; int cnt = 50; while (cnt--) { double l2 = (l * 2 + r) / 3; double r2 = (l + r * 2) / 3; if (calc(i, l2) > calc(i, r2)) { l = l2; } else { r = r2; } } res += calc(i, r); } cout << res << '\n'; }