#include #include using namespace std; using namespace numbers; int main(){ cin.tie(0)->sync_with_stdio(0); cin.exceptions(ios::badbit | ios::failbit); int n, m; cin >> n >> m; vector> a(n * m); vector pos(n, vector(m)); for(auto i = 0; i < n * m; ++ i){ cin >> a[i][0] >> a[i][1], -- a[i][0], -- a[i][1]; pos[a[i][0]][a[i][1]] = i; } int res = numeric_limits::max(); for(auto xs = 0; xs + 5 <= n + 1; ++ xs){ for(auto y = 0; y < m; ++ y){ array p; for(auto dx = 0; dx < 5; ++ dx){ p[dx] = pos[(xs + dx) % n][y]; } ranges::sort(p); int last = -1, cur = -1; for(auto pick = 0; pick < 5; ++ pick){ int i = p[pick], jump = 5 - pick; cur += (i - last + jump - 1) / jump; last += (i - last + jump - 1) / jump * jump; } res = min(res, cur); } } cout << res << "\n"; return 0; } /* */ //////////////////////////////////////////////////////////////////////////////////////// // // // Coded by Aeren // // // ////////////////////////////////////////////////////////////////////////////////////////