#include "testlib.h" #include #include using namespace std; #define rep(i,n) for(int i=0; i<(n); i++) int N,M; int pos[501][500]={}; int sfPos[5]={}; int solve_per_sfPos(){ int ans=0; int remain=0, p=0; rep(i,5){ remain+=sfPos[i]-p; p=sfPos[i]+1; ans+=remain/(5-i); remain%=(5-i); } return ans; } int main(){ registerValidation(); N = inf.readInt(5,500); inf.readSpace(); M = inf.readInt(1,500); inf.readEoln(); rep(i,N*M){ int n = inf.readInt(1,N); inf.readSpace(); int m = inf.readInt(1,M); inf.readEoln(); n--; m--; pos[n][m]=i; } rep(i,M) pos[N][i]=pos[0][i]; inf.readEof(); int ans=1000000000; for(int ns=0; ns<=N-4; ns++) rep(m,M) { rep(i,5) sfPos[i]=pos[ns+i][m]; sort(sfPos,sfPos+5); ans=min(ans,solve_per_sfPos()); } cout<