/* -*- coding: utf-8 -*- * * 2463.cc: No.2463 繧ケ繝医Ξ繝シ繝医ヵ繝ゥ繝・す繝・ - yukicoder */ #include #include using namespace std; /* constant */ const int MAX_N = 500; const int MAX_M = 500; const int MAX_NM = MAX_N * MAX_M; const int H = 5; const int INF = 1 << 30; /* typedef */ /* global variables */ int rs[MAX_NM], ss[MAX_NM]; int aps[MAX_M][MAX_N + 1]; /* subroutines */ int check(int ps[], int l) { int qs[H]; copy(ps + l, ps + l + H, qs); sort(qs, qs + H); int op = 0, i = 0; while (i < H && qs[i] < H) i++; int x = H; while (i < H) { int d = H - i; int dop = (qs[i] - x) / d + 1; op += dop; x += d * dop; while (i < H && qs[i] < x) i++; } return op; } /* main */ int main() { int n, m; scanf("%d%d", &n, &m); int nm = n * m; for (int i = 0; i < nm; i++) { scanf("%d%d", rs + i, ss + i), rs[i]--, ss[i]--; aps[ss[i]][rs[i]] = i; if (rs[i] == 0) aps[ss[i]][n] = i; } int minop = INF; for (int si = 0; si < m; si++) { for (int l = 0; l + H - 1 <= n; l++) minop = min(minop, check(aps[si], l)); } printf("%d\n", minop); return 0; }