/* -*- coding: utf-8 -*- * * 2463.cc: No.2463 繧ケ繝医Ξ繝シ繝医ヵ繝ゥ繝・す繝・ - yukicoder */ #include #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 INF = 1 << 30; /* typedef */ using vi = vector; /* global variables */ int rs[MAX_NM], ss[MAX_NM]; vi avs[MAX_M]; bool used[MAX_N + 1]; /* subroutines */ /* 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]--; avs[ss[i]].push_back(rs[i]); } int minop = INF; for (int si = 0; si < m; si++) { fill(used, used + n + 1, false); int l = -1, r = -1, x = -1; for (auto ri: avs[si]) { used[ri] = true; int l0 = ri, r0 = ri; while (l0 > 0 && used[l0 - 1] && r0 - (l0 - 1) <= 4) l0--; while (r0 < n && used[r0 + 1] && (r0 + 1) - l0 <= 4) r0++; if (r0 - l0 == 4) { l = l0, r = r0, x = ri; break; } if (ri == 0) { used[n] = true; l0 = n, r0 = n; while (l0 > 0 && used[l0 - 1] && r0 - (l0 - 1) <= 4) l0--; if (r0 - l0 == 4) { l = l0, r = r0, x = n; break; } } } //printf(" si=%d, %d,%d,%d\n", si, l, r, x); int op = 0, c = 0; for (int i = 0; i < 5; i++) if (ss[i] == si && ((l <= rs[i] && rs[i] <= r) || (rs[i] == 0 && r == n))) c++; for (int i = 5; c < 5 && i < nm;) { op++; int d = 5 - c; while (d > 0) { if (ss[i] == si && ((l <= rs[i] && rs[i] <= r) || (rs[i] == 0 && r == n))) c++; d--, i++; } } minop = min(minop, op); } printf("%d\n", minop); return 0; }