n,m=map(int,input().split()) c=[[] for i in range(m)] for i in range(n*m): s,t=map(int,input().split()) s-=1 t-=1 c[t].append((i,s)) for i in range(m): c[i].sort() a=n*m for _ in range(2): for i in range(m): q=[-1]*(n+1) for p,x in c[i]: q[x]=p for j in range(x-4,x+1): if 0<=j=0 for gg in g[1:]]): b=0 for k in range(5): b+=(g[k+1]-g[k]-1+5-k-1)//(5-k) a=min(a,b) for i in range(m): for j in range(len(c[i])): if c[i][j][1]==0: c[i][j]=(c[i][j][0],n) print(a)