// #pragma GCC target("avx2") // #pragma GCC optimize("O3") // #pragma GCC optimize("unroll-loops") #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using lg = long long; using pii = pair; using pll = pair; #define TEST cerr << "TEST" << endl #define AMARI 998244353 // #define AMARI 1000000007 #define TEMOTO ((sizeof(long double) == 16) ? false : true) #define TIME_LIMIT 1980 * (TEMOTO ? 1 : 1000) #define el '\n' #define El '\n' int func(int a, int b, int c, int d, int e){ vector dif = {a, b - a, c - b, d - c, e - d}; int ans = 0,yoryoku = 0; for(int i = 0; i < 5; i++){ if(yoryoku >= dif[i]){ yoryoku -= dif[i]; continue; } dif[i] -= yoryoku; ans += (dif[i] - 1) / (5 - i) + 1; yoryoku = (5 - i) - dif[i] % (5 - i); if(dif[i] % (5 - i) == 0)yoryoku = 0; } return ans; } #define MULTI_TEST_CASE false void solve(void){ int n, m; cin >> n >> m; // basyo[番号][色] := そのカードの場所 vector> basyo(n, vector(m)); for (int i = 0; i < n * m; i++){ int tn, tm; cin >> tn >> tm; tn--; tm--; basyo[tn][tm] = i + 1; } int ans = INT_MAX; for (int i = 0; i < m; i++){ for(int j = 0; j < n - 4; j++){ vector v = {basyo[j][i],basyo[j + 1][i],basyo[j + 2][i],basyo[j + 3][i],basyo[j + 4][i]}; sort(v.begin(),v.end()); ans = min(ans,func(v[0],v[1],v[2],v[3],v[4])); } vector u = {basyo[i][0],basyo[i][n - 1],basyo[i][n - 2],basyo[i][n - 3],basyo[i][n - 4]}; sort(u.begin(),u.end()); ans = min(ans,func(u[0],u[1],u[2],u[3],u[4])); } cout << ans - 1 << el; return; } void calc(void){ return; } int main(void){ cin.tie(nullptr); ios::sync_with_stdio(false); calc(); int t = 1; if (MULTI_TEST_CASE)cin >> t; while (t--){ solve(); } return 0; }