#include using namespace std; using ll = long long; int main(){ ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; vector> A(m, vector(n)); vector> a(n * m); for(int i = 0; i < n * m; i++){ int u, v; cin >> u >> v; u--, v--; a[i] = make_pair(u, v); A[v][u] = i + 1; } int ans = 1 << 30; auto f = [&](vector b){ sort(b.begin(), b.end()); int cur = 5, s = 0; for(int i = 0; i < 5; i++){ if(cur >= b[i]) continue; int d = (b[i] - cur + 4 - i) / (5 - i); cur += d * (5 - i); s += d; } return s; }; vector c(5); for(int i = 0; i < m; i++){ for(int j = 0; j + 5 <= n; j++){ for(int k = 0; k < 5; k++){ c[k] = A[i][j + k]; } ans = min(ans, f(c)); } c[0] = A[i][0]; for(int j = 0; j < 4; j++){ c[j + 1] = A[i][n - 1 - j]; } ans = min(ans, f(c)); } cout << ans << '\n'; }