#include int main () { int n = 0; int m = 0; int ni = 0; int mi = 0; int res = 0; int ans = 0; int pos[500][500] = {}; int tmp[5] = {}; res = scanf("%d", &n); res = scanf("%d", &m); for (int i = 0; i < n*m; i++) { res = scanf("%d", &ni); res = scanf("%d", &mi); pos[mi-1][ni-1] = i; } ans = n*m; for (int i = 0; i < m; i++) { for (int j = 0; j < n-3; j++) { int tmpcnt = 0; int tmppos = 4; for (int k = 0; k < 5; k++) { tmp[k] = pos[i][(j+k)%n]; } for (int k = 4; k > 0; k--) { for (int l = 0; l < k; l++) { if (tmp[l] > tmp[l+1]) { int s = tmp[l]; tmp[l] = tmp[l+1]; tmp[l+1] = s; } } } tmpcnt = tmp[0]/5; tmppos = (1+tmp[0]/5)*5-1; if (tmppos < tmp[1]) { tmpcnt += 1+(tmp[1]-tmppos-1)/4; tmppos += (1+(tmp[1]-tmppos-1)/4)*4; } if (tmppos < tmp[2]) { tmpcnt += 1+(tmp[2]-tmppos-1)/3; tmppos += (1+(tmp[2]-tmppos-1)/3)*3; } if (tmppos < tmp[3]) { tmpcnt += 1+(tmp[3]-tmppos-1)/2; tmppos += (1+(tmp[3]-tmppos-1)/2)*2; } if (tmppos < tmp[4]) { tmpcnt += tmp[4]-tmppos; tmppos = tmp[4]; } if (tmpcnt < ans) { ans = tmpcnt; } } } printf("%d\n", ans); return 0; }