You are given a rectangular matrix of size $n \times m$ consisting of integers from $1$ to $2 \cdot 10^5$.

In one move, you can:  choose any element of the matrix and change its value to any integer between $1$ and $n \cdot m$, inclusive;  take any column and shift it one cell up cyclically (see the example of such cyclic shift below). 

A cyclic shift is an operation such that you choose some $j$ ($1 \le j \le m$) and set $a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \dots, a_{n, j} := a_{1, j}$ simultaneously. [Image] Example of cyclic shift of the first column 

You want to perform the minimum number of moves to make this matrix look like this: $\left. \begin{array}{|c c c c|} \hline 1 & {2} & {\ldots} & {m} \\{m + 1} & {m + 2} & {\ldots} & {2m} \\{\vdots} & {\vdots} & {\ddots} & {\vdots} \\{(n - 1) m + 1} & {(n - 1) m + 2} & {\ldots} & {nm} \\ \hline \end{array} \right.$ 

In other words, the goal is to obtain the matrix, where $a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$ (i.e. $a_{i, j} = (i - 1) \cdot m + j$) with the minimum number of moves performed.


-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5, n \cdot m \le 2 \cdot 10^5$) — the size of the matrix.

The next $n$ lines contain $m$ integers each. The number at the line $i$ and position $j$ is $a_{i, j}$ ($1 \le a_{i, j} \le 2 \cdot 10^5$).


-----Output-----

Print one integer — the minimum number of moves required to obtain the matrix, where $a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$ ($a_{i, j} = (i - 1)m + j$).


-----Examples-----
Input
3 3
3 2 1
1 2 3
4 5 6

Output
6

Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12

Output
0

Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12

Output
2



-----Note-----

In the first example, you can set $a_{1, 1} := 7, a_{1, 2} := 8$ and $a_{1, 3} := 9$ then shift the first, the second and the third columns cyclically, so the answer is $6$. It can be shown that you cannot achieve a better answer.

In the second example, the matrix is already good so the answer is $0$.

In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is $2$.

Source: codeforces | Difficulty: HARD
Tags: Mathematics

Implementation

Greedy algorithms


Solutions:
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
(n, m) = Ri()
lis = []
for i in range(n):
	temp = Ri()
	temp = [i - 1 for i in temp]
	lis.append(temp)
ans = 0
for i in range(m):
	temp = 10 ** 18
	dic = {}
	for j in range(n):
		if lis[j][i] % m == i:
			if lis[j][i] // m < n:
				noshifts = (j - lis[j][i] // m) % n
				dic[noshifts] = dic.get(noshifts, 0) + 1
	for j in range(n):
		temp = min(temp, n - dic.get(j, 0) + j)
	ans += temp
print(ans)


(n, m) = map(int, input().split())
c = [[] for i in range(m)]
for i in range(n):
	a = list(map(int, input().split()))
	for j in range(m):
		c[j] += [a[j]]
total = 0

def match(arr, start, m):
	c = 0
	for i in range(len(arr)):
		if arr[i] != start + i * m:
			c += 1
	return c
t = 0
for i in range(m):
	col = c[i]
	mina = [n + i for i in range(n)]
	for j in range(n):
		col[j] = (col[j] - i - 1) // m + 1 if (col[j] - i - 1) % m == 0 else -1
		if col[j] > n * m:
			col[j] = -1
	for j in range(n):
		if col[j] != -1:
			mina[(n - (col[j] - j - 1)) % n] -= 1
	t += min(mina)
print(t)


import sys
(n, m) = map(int, input().split())
lis_2d = [[int(i) - 1 for i in input().split()] for i in range(n)]
final = 0
for j in range(m):
	count = [0] * n
	for i in range(n):
		if lis_2d[i][j] % m == j:
			pos = lis_2d[i][j] // m
			if pos < n:
				k = (i - pos + n) % n
				count[k] += 1
	ans1 = sys.maxsize
	for i in range(len(count)):
		ans = n - count[i] + i
		if ans < ans1:
			ans1 = ans
	final += ans1
print(final)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter
from itertools import combinations
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192
from sys import stderr

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def pow(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def gcd(a, b):
	if a == b:
		return a
	while b > 0:
		(a, b) = (b, a % b)
	return a

def prefix_sum(ar):
	return list(accumulate(ar))

def suffix_sum(ar):
	return list(accumulate(ar[::-1]))[::-1]

def N():
	return int(inp())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]

def YES():
	print('YES')

def NO():
	print('NO')

def Yes():
	print('Yes')

def No():
	print('No')
from collections import defaultdict

def numberOfSetBits(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	return ((i + (i >> 4) & 252645135) * 16843009 & 4294967295) >> 24

class MergeFind:

	def __init__(self, n):
		self.parent = list(range(n))
		self.size = [1] * n
		self.num_sets = n

	def find(self, a):
		to_update = []
		while a != self.parent[a]:
			to_update.append(a)
			a = self.parent[a]
		for b in to_update:
			self.parent[b] = a
		return self.parent[a]

	def merge(self, a, b):
		a = self.find(a)
		b = self.find(b)
		if a == b:
			return
		self.num_sets -= 1
		self.parent[a] = b
		self.size[b] += self.size[a]

	def set_size(self, a):
		return self.size[self.find(a)]

	def __len__(self):
		return self.num_sets

def lcm(a, b):
	return abs(a // gcd(a, b) * b)

def solve():
	(n, m) = sep()
	ans = 0
	ar = [lis() for _ in range(n)]
	for j in range(m):
		d = defaultdict(int)
		w = 0
		t_ans = 9999999999999999
		for i in range(n):
			ar[i][j] -= 1
			if ar[i][j] % m != j:
				w += 1
				continue
			t = ar[i][j] // m
			diff = i - t
			if -n < diff < 0:
				diff += n
			d[diff] += 1
		for i in range(n):
			t = n + i - d[i]
			t_ans = min(t, t_ans)
		ans += t_ans
	print(ans)
solve()


(n, m) = (int(i) for i in input().split())
a = [[int(i) for i in input().split()] for _ in range(n)]
res = 0
for j in range(m):
	b = [0] * n
	for i in range(n):
		if a[i][j] <= n * m and (a[i][j] - j - 1) % m == 0:
			pos = (a[i][j] - j - 1) // m
			shift = i - pos if i >= pos else i - pos + n
			b[shift] += 1
	res += min((i + n - b[i] for i in range(n)))
print(res)


(n, m) = map(int, input().split())
tbl = []
for _ in range(n):
	tbl.append(list(map(int, input().split())))
l = [[k + n for k in range(n)] for _ in range(m)]
for i in range(m):
	for j in range(n):
		a = (tbl[j][i] - 1) // m
		b = (tbl[j][i] - 1) % m
		if a <= n - 1 and b == i:
			l[i][(j - a) % n] -= 1
ans = 0
for i in range(m):
	ans += min(l[i])
print(ans)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=10 ** 6, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(10)]
pp = [0] * 10

def SieveOfEratosthenes(n=10):
	p = 2
	c = 0
	while p * p <= n:
		if prime[p] == True:
			c += 1
			for i in range(p, n + 1, p):
				pp[i] += 1
				prime[i] = False
		p += 1

def binarySearch(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = arr[n - 1]
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] >= key:
			res = arr[mid]
			right = mid - 1
		else:
			left = mid + 1
	return res

def binarySearch1(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = arr[0]
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] > key:
			right = mid - 1
		else:
			res = arr[mid]
			left = mid + 1
	return res
(n, m) = map(int, input().split())
a = []
for i in range(n):
	b = list(map(int, input().split()))
	a.append(b)
res = 0
for i in range(m):
	b = [0] * n
	for j in range(n):
		num = a[j][i] - 1
		if num % m != i:
			continue
		k = num // m
		if k < n:
			if k > j:
				b[n - k + j] += 1
			else:
				b[j - k] += 1
	r = 2 * n
	for j in range(n):
		r = min(r, n - b[j] + j)
	res += r
print(res)


import os
import sys
from io import BytesIO, IOBase
from collections import Counter

def main():
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for _ in range(n)]
	ans = 0
	for i in range(m):
		b = Counter()
		for j in range(n):
			b[m * j + i + 1] = j + 1
		c = Counter()
		for j in range(n):
			z = b[a[j][i]]
			if z:
				c[(j - z + 1) % n] += 1
		mi = n
		for j in c:
			mi = min(mi, j + n - c[j])
		ans += mi
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.buffer.readline
ans = 0
(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
for j in range(m):
	mn_moves_for_row = n
	loc = {}
	for i in range(n):
		loc[i * m + j + 1] = i
	events = [0] * (n + 1)
	for i in range(n):
		if a[i][j] in loc:
			shifts = (i - loc[a[i][j]] + n) % n
			events[shifts] += 1
			events[shifts + 1] -= 1
	matches = 0
	for shifts in range(n):
		matches += events[shifts]
		mn_moves_for_row = min(mn_moves_for_row, shifts + n - matches)
	ans += mn_moves_for_row
print(ans)


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
ans = [[0 for i in range(m)] for i in range(n)]
for i in range(n):
	q = list(map(int, input().split()))
	for j in range(len(q)):
		ans[i][j] = q[j]
col = []
maxa = 0
total = 0
from collections import *
for x in range(m):
	col = [x + 1]
	for i in range(1, n):
		col.append(col[-1] + m)
	al = defaultdict(int)
	for i in range(len(col)):
		al[col[i]] = i + 1
	dns = []
	for j in range(n):
		dns.append(ans[j][x])
	dr = defaultdict(int)
	for i in range(len(dns)):
		pos = i + 1
		value = dns[i]
		if al[value] == 0:
			continue
		if al[value] <= pos:
			dr[pos - al[value]] += 1
		else:
			dr[pos + len(dns) - al[value]] += 1
	parts = 0
	costs = 0
	maxa = 0
	for i in dr:
		maxa = max(maxa, dr[i] - i)
	total += n - maxa
print(total)


from collections import defaultdict, Counter

def main():
	(n, m) = [int(x) for x in input().split()]
	grid = [[-1] * (m + 1) for i in range(n + 1)]
	for i in range(1, n + 1):
		arr = [int(x) for x in input().split()]
		for j in range(1, m + 1):
			grid[i][j] = arr[j - 1]
	ans = 0
	for j in range(1, m + 1):
		cur_col_ans = 1000000000.0
		off_by_above = defaultdict(lambda : 0)
		off_by_below = defaultdict(lambda : 0)
		for i in range(1, n + 1):
			opt = j + (i - 1) * m
			off_by_below[grid[i][j] - opt] += 1
		for i in range(1, n + 1):
			d = m * (i - 1)
			opt = j + (i - 1) * m
			temp = i - 1
			temp += n - i + 1 - off_by_below[-d]
			temp += i - 1 - off_by_above[(n + 1 - i) * m]
			cur_col_ans = min(cur_col_ans, temp)
			off_by_below[grid[i][j] - opt] -= 1
			off_by_above[grid[i][j] - opt] += 1
		ans += cur_col_ans
	print(ans)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def push(d, x):
	if x not in d:
		d[x] = 0
	d[x] += 1

def solve(a, x, n, m):
	need = {x + i * m: i for i in range(n)}
	d = {}
	for (i, val) in enumerate(a):
		if val in need:
			push(d, (i - need[val] + n) % n)
	min_ = n
	for (move, num) in d.items():
		min_ = min(min_, move + n - num)
	return min_
(n, m) = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(n)]
min_ = 0
for x in range(1, m + 1):
	a = [A[i][x - 1] for i in range(n)]
	min_ += solve(a, x, n, m)
print(min_)


import sys, math
import io, os
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
mod = int(1000000000.0) + 7

def update(BIT, v, w):
	while v <= n:
		BIT[v] += w
		v += v & -v

def getvalue(BIT, v):
	ANS = 0
	while v != 0:
		ANS += BIT[v]
		v -= v & -v
	return ANS

def bisect_on_BIT(BIT, x):
	if x <= 0:
		return 0
	ANS = 0
	h = 1 << n - 1
	while h > 0:
		if ANS + h <= n and BIT[ANS + h] < x:
			x -= BIT[ANS + h]
			ANS += h
		h //= 2
	return ANS + 1
(n, m) = mdata()
a = [mdata() for i in range(n)]
ans = 0
for i in range(m):
	d = dd(int)
	for j in range(n):
		if (a[j][i] - 1) % m == i and (a[j][i] - 1) // m < n:
			d[(j - (a[j][i] - 1) // m) % n] += 1
	min1 = n
	for j in d:
		min1 = min(min1, j + n - d[j])
	ans += min1
out(ans)


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
CR = [list(map(int, input().split())) for i in range(n)]
for i in range(n):
	for j in range(m):
		CR[i][j] -= 1
MAX = n * m
ANS = 0
for i in range(m):
	SCORE = [0] * n
	for j in range(n):
		if CR[j][i] % m == i % m and 0 <= CR[j][i] < MAX:
			x = (CR[j][i] - i % m) // m
			SCORE[(j - x) % n] += 1
	ANS += min([n + j - SCORE[j] for j in range(n)])
print(ANS)


from collections import defaultdict

def solve():
	(n, m) = map(int, input().split())
	l = [list(map(int, input().split())) for i in range(n)]
	for i in range(n):
		for j in range(m):
			l[i][j] -= 1
	ans = 0
	for i in range(m):
		d = defaultdict(int)
		for j in range(n):
			if l[j][i] % m == i and l[j][i] < n * m:
				d[(j + n - l[j][i] // m) % n] += 1
		mn = n
		for p in d.items():
			if p[0] + (n - p[1]) < mn:
				mn = p[0] + (n - p[1])
		ans += mn
	print(ans)
solve()


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
ans = 0
for i in range(m):
	cnt = [n + j for j in range(n)]
	j = (i + 1) % m
	for k in range(n):
		if a[k][i] % m ^ j or not 1 <= a[k][i] <= n * m:
			continue
		x = i + k * m + 1
		cnt[(x - a[k][i]) % (n * m) // m] -= 1
	ans += min(cnt)
print(ans)


import sys
(n, m) = [int(i) for i in sys.stdin.readline().split()]
d = []
for j in range(n):
	d.append([int(i) for i in sys.stdin.readline().split()])
dd = [[d[j][i] for j in range(n)] for i in range(m)]
ans = 0
for i in range(m):
	diff = [(j * m + i + 1 - dd[i][j]) % (n * m) if dd[i][j] <= n * m else -1 for j in range(n)]
	dic = {}
	for dif in diff:
		if dif in dic:
			dic[dif] += 1
		else:
			dic[dif] = 1
	mn = n
	for sh in range(n):
		tee = m * sh
		am = 0
		if tee in dic:
			am = dic[tee]
		mn = min(n - am + sh, mn)
	ans += mn
print(ans)


import sys, math
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())
t = 1
for tt in range(t):
	(n, m) = invr()
	a = []
	for i in range(n):
		a.append(inlt())
	q = 0
	for j in range(m):
		qw = [0] * n
		for i in range(n):
			if (a[i][j] - (j + 1)) % m == 0:
				w = (a[i][j] - (j + 1)) // m
				if w < n:
					qw[(i - w) % n] = qw[(i - w) % n] + 1
		qq = 0
		for (i, ww) in enumerate(qw):
			qq = max(qq, ww - i)
		q = q + n - qq
	print(q)


import sys
inp = sys.stdin.readline
input = lambda : inp().strip()
flush = sys.stdout.flush

def iin():
	return int(input())

def lin():
	return list(map(int, input().split()))

def main():
	(n, m) = lin()
	a = [lin() for i in range(n)]
	a = [[a[j][i] for j in range(n)] for i in range(m)]
	ans = 0
	for i in range(m):
		dc = {}
		for j in range(n):
			x = a[i][j] - i - 1
			if x >= 0 and x % m == 0 and (x // m < n):
				try:
					dc[(j - x // m) % n] += 1
				except:
					dc[(j - x // m) % n] = 1
		(ch1, ch2) = (0, -1)
		ch3 = n
		for i in dc:
			ch3 = min(ch3, i + n - dc[i])
		ans += min(n, ch3)
	print(ans)
main()


import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
(n, m) = [int(x) for x in input().split()]
a = [[int(x) for x in input().split()] for _ in range(n)]
max_value = n * m
moves = 0
for i in range(m):
	saves = {x: -x for x in range(n)}
	for (j, v) in enumerate([row[i] for row in a]):
		if v % m == (i + 1) % m and v <= max_value:
			saves[(j * m + i + 1 - v) // m % n] += 1
	moves += n - max(0, max(saves.values()))
print(moves)


import math
(n, m) = map(int, input().split())
grid = []
for _ in range(n):
	grid.append(list(map(int, input().split())))
ans = 0
for c in range(m):
	cnt = [0 for _ in range(n)]
	for i in range(n):
		grid[i][c] -= c + 1
		if grid[i][c] % m == 0 and grid[i][c] <= (n - 1) * m:
			cnt[(n + i - grid[i][c] // m) % n] += 1
	mn = n + 5
	for i in range(n):
		mn = min(mn, i + n - cnt[i])
	ans += mn
print(ans)


import collections

def solve():
	(n, m) = input().split()
	(n, m) = (int(n), int(m))
	nums = []
	for i in range(n):
		row = [int(num) - 1 for num in input().split()]
		nums.append(row)
	tot_moves = 0
	for j in range(m):
		count = collections.defaultdict(int)
		for i in range(n):
			num = nums[i][j]
			exp_i = num // m
			if exp_i < n and num % m == j:
				num_shift = (i - exp_i + n) % n
				count[num_shift] += 1
		col_moves = n
		for num_shift in range(0, n):
			moves = n - count[num_shift] + num_shift
			col_moves = min(col_moves, moves)
		tot_moves += col_moves
	print(tot_moves)
solve()


from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from heapq import heappush, heappop
import math
import io
import os
import math
import bisect

def isPrime(x):
	for i in range(2, x):
		if i * i > x:
			break
		if x % i == 0:
			return False
	return True

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n // i
	if n > 2:
		l.append(n)
	return l

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def digits(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def ceil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

def mapin():
	return map(int, input().split())
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def solve(l, n, m, c, d):
	s = [0] * n
	for i in range(n):
		if l[i] % m == c:
			a = l[i] // m
			a -= d
			if a >= n:
				continue
			if a - i >= 0:
				a = (i + n - a) % n
			else:
				a = (i - a) % n
			if a < n:
				s[a] += 1
	ans = 1000000000.0
	for i in range(n):
		temp = n
		temp -= s[i]
		temp += i
		ans = min(ans, temp)
	return ans
(n, m) = mapin()
sa = []
for i in range(m):
	sa.append([0] * n)
for i in range(n):
	tt = [int(x) for x in input().split()]
	for j in range(m):
		sa[j][i] = tt[j]
ans = 0
for j in range(m):
	a = solve(sa[j], n, m, (j + 1) % m, (j + 1) // m)
	ans += a
print(ans)


(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
ans = 0
for j in range(m):
	cnt = [0 for i in range(n)]
	cur = n
	for i in range(n):
		if (a[i][j] - (j + 1)) % m == 0 and a[i][j] <= m * n:
			x = int((m * i - (a[i][j] - (j + 1))) / m)
			x += n
			x %= n
			cnt[x] += 1
	for i in range(n):
		cur = min(cur, i + n - cnt[i])
	ans += cur
print(ans)


import os
import sys
from atexit import register
from io import StringIO
sys.stdout = StringIO()
register(lambda : os.write(1, sys.stdout.getvalue().encode()))

def minimize(column, target):
	size = len(column)
	target_idxs = {}
	column_shift_counts = {}
	for i in range(size):
		target_idxs[target[i]] = i
		column_shift_counts[i] = 0
	for i in range(size):
		k = column[i]
		if k in target_idxs:
			column_shift_counts[(i - target_idxs[k]) % size] += 1
	return min([size - column_shift_counts[i] + i for i in range(size)])
[n, m] = [int(k) for k in input().split()]
a = []
for _ in range(n):
	a.append([int(k) for k in input().split()])
columns = [[a[j][k] for j in range(n)] for k in range(m)]
print(sum([minimize(columns[k], list(range(k + 1, n * m + k + 1, m))) for k in range(m)]))


from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n').split(' ')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
(n, m) = li()
l = []
ans = 0
for i in range(n):
	l.append(li())
for j in range(1, m + 1):
	cnt = Counter()
	for i in range(1, n + 1):
		tot = 0
		ele = l[i - 1][j - 1]
		if ele > n * m:
			continue
		if j == m:
			if ele % m:
				continue
		elif ele % m != j:
			continue
		pos = math.ceil(ele / m)
		if pos > i:
			dist = i + (n - pos)
		else:
			dist = i - pos
		cnt[dist] += 1
	temp = n
	if len(cnt):
		for i in cnt:
			temp = min(temp, i + (n - cnt[i]))
	ans += temp
print(ans)


import sys
from collections import defaultdict, deque
inp = sys.stdin.readline
read = lambda : list(map(int, inp().split()))

def e():
	res = 0
	(n, m) = read()
	mat = [None] * n
	for i in range(n):
		mat[i] = read()
	for col in range(m):
		b = [0] * n
		for row in range(n):
			elem = mat[row][col]
			place = row * m + col + 1
			if elem <= n * m and (place - elem) % m == 0:
				shift = (place - elem) // m if place >= elem else (n * m + place - elem) // m
				b[shift] += 1
		res += min((i + n - b[i] for i in range(n)))
	print(res)

def d():
	ans = ''
	mex = 0
	(q, x) = read()
	arr = [0] * q + [0]
	dic = {i: deque([i]) for i in range(x)}
	for i in dic:
		while dic[i][-1] + x < q + 1:
			dic[i].append(dic[i][-1] + x)
	for _ in range(q):
		n = int(inp())
		ind = dic[n % x].popleft() if dic[n % x] else n % x
		arr[ind] = 1
		while arr[mex] == 1:
			mex += 1
		ans += str(mex) + '\n'
	print(ans)
e()


from collections import Counter
from sys import stdin

def input():
	return next(stdin)

def main():
	(n, m) = map(int, input().split())
	aaa = []
	for _ in range(n):
		aaa.append([int(a) for a in input().split()])
	aaar = list(zip(*aaa))
	t = m * n
	cost = 0
	for (i, aa) in enumerate(aaar, 1):
		rot = Counter()
		for (j, a) in enumerate(aa):
			if a % m == i % m and aa[j] <= t:
				rot[(j - (a - 1) // m) % n] += 1
		for j in range(n):
			rot[j] -= j
		best = rot.most_common(1)[0][1]
		cost += n - max(best, 0)
	print(cost)
main()


import sys
input = sys.stdin.readline
import math
import copy
import collections
from collections import deque
inf = 10 ** 18
(n, m) = list(map(int, input().split()))
arr = []
for i in range(n):
	arr.append(list(map(int, input().split())))
ans = 0
for i in range(m):
	vals = []
	for j in range(n):
		if arr[j][i] >= i + 1 and arr[j][i] <= i + 1 + m * (n - 1) and ((arr[j][i] - (i + 1)) % m == 0):
			vals.append(-(arr[j][i] - (i + 1 + m * j)) // m % n)
		else:
			vals.append(10 ** 18)
	counts = dict()
	for val in vals:
		if val not in counts:
			counts[val] = 0
		counts[val] += 1
	total = 0
	for num in counts:
		total += counts[num]
	add = 10 ** 18
	for num in counts:
		if num == 10 ** 18:
			continue
		temp = num + total - counts[num]
		add = min(add, temp)
	ans += min(add, n)
print(ans)


arr1 = str(input())
arr2 = arr1.split()
r = int(arr2[0])
c = int(arr2[1])
gh = [0 for _ in range(c)]
arr = [gh[:] for _ in range(r)]
for i in range(r):
	t2 = str(input())
	t1 = t2.split()
	for j in range(c):
		arr[i][j] = int(t1[j]) - 1
totalt = 0
for i in range(c):
	tmp = {}
	mins = r
	for j in range(r):
		v = arr[j][i]
		remainder = v % c
		if remainder != i:
			continue
		kt = v // c
		if kt >= r:
			continue
		gttt = kt
		kt = j - kt
		if kt < 0:
			kt = j + 1 + (r - 1) - gttt
		if kt not in tmp:
			tmp[kt] = 1
		else:
			tmp[kt] += 1
	for (key, value) in tmp.items():
		diff = r - value + key
		mins = min(mins, diff)
	totalt += mins
print(totalt)


(m, n) = map(int, input().split())
a = []
ans = 0
for y in range(m):
	a.append(list(map(int, input().split())))
for i in range(n):
	ch = (i + 1) % n
	ar = [0 for y in range(m)]
	for j in range(m):
		if a[j][i] % n == ch and a[j][i] <= m * n:
			ind = (a[j][i] - 1) // n
			if j >= ind:
				ar[j - ind] += 1
			else:
				ar[m + j - ind] += 1
	maxx = 0
	indmax = -1
	for j in range(m):
		if maxx < ar[j] - j:
			maxx = ar[j] - j
			indmax = j
	if indmax == -1:
		ans += m
	else:
		ans += indmax + m - ar[indmax]
print(ans)


def solve(column, start, n, m):
	shiftCnts = [0 for _ in range(n)]
	for actualPosition in range(n):
		v = column[actualPosition]
		if v > n * m:
			continue
		desiredPosition = (v - 1) // m
		desiredValueAtDesiredPosition = start + m * desiredPosition
		if desiredValueAtDesiredPosition != v:
			continue
		shiftsRequired = (actualPosition - desiredPosition + n) % n
		shiftCnts[shiftsRequired] += 1
	ans = inf
	for shifts in range(n):
		ans = min(ans, shifts + n - shiftCnts[shifts])
	return ans

def main():
	(n, m) = readIntArr()
	arr = []
	for _ in range(n):
		arr.append(readIntArr())
	ans = 0
	for j in range(m):
		column = []
		for i in range(n):
			column.append(arr[i][j])
		ans += solve(column, j + 1, n, m)
	print(ans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(*args):
	assert len(args) >= 2, 'makeArr args should be (default value, dimension 1, dimension 2,...'
	if len(args) == 2:
		return [args[0] for _ in range(args[1])]
	else:
		return [makeArr(args[0], *args[2:]) for _ in range(args[1])]

def queryInteractive(x, y):
	print('? {} {}'.format(x, y))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


import sys
input = sys.stdin.readline
(n, m) = list(map(int, input().split()))
arr = [[] for i in range(m)]
for _ in range(n):
	l = list(map(int, input().split()))
	for i in range(m):
		arr[i].append(l[i])
out = 0
for i in range(m):
	l = arr[i]
	best = list(range(0, -n, -1))
	for j in range(n):
		v = l[j] - i - 1
		if v % m == 0:
			correct = v // m
			if 0 <= correct < n:
				best[j - correct] += 1
	out += n - max(best)
print(out)


import os
import sys
from io import BytesIO, IOBase

def main():
	(n, m) = map(int, input().split())
	arr = []
	for _ in range(n):
		arr.append(list(map(lambda x: int(x) - 1, input().split())))
	ans = 0

	def solvemin(x):
		zz = 0
		cnt = [0] * n
		for i in range(n):
			val = arr[i][x] - x
			if val % m == 0 and val // m < n:
				cnt[(i - val // m + n) % n] += 1
		zz = float('inf')
		for i in range(n):
			zz = min(zz, n - cnt[i] + i)
		return zz
	for i in range(m):
		ans += solvemin(i)
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


INF = 10 ** 10

def main():
	(n, m) = get_list()
	mat = [get_list() for _ in range(n)]
	res = 0
	for j in range(m):
		shifts = [0] * n
		for i in range(n):
			if (mat[i][j] - (j + 1)) % m == 0:
				org = (mat[i][j] - (j + 1)) // m
				if 0 <= org < n:
					shifts[(i - org) % n] += 1
		drop = 0
		for (i, ele) in enumerate(shifts):
			drop = max(drop, ele - i)
		res += n - drop
	print(res)
import sys
from collections import defaultdict, Counter
from bisect import bisect_left, bisect_right
import math
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
out = []
get_int = lambda : int(input())
get_list = lambda : list(map(int, input().split()))
main()
print(*out, sep='\n')


(n, m) = tuple(map(int, input().split()))
arr = [list(map(int, input().split())) for _ in range(n)]

def getMinMoves(arr, n, m):
	moves = 0
	for j in range(m):
		cnts = [0] * n
		biggest = (n - 1) * m + j
		for i in range(n):
			if (arr[i][j] - 1) % m == j and arr[i][j] - 1 <= biggest:
				pos = (arr[i][j] - 1 - j) // m
				if pos > i:
					cnts[n - pos + i] += 1
				else:
					cnts[i - pos] += 1
		min_moves = float('inf')
		for shft in range(n):
			match_cnt = cnts[shft]
			min_moves = min(min_moves, shft + n - match_cnt)
		moves += min_moves
	return moves
print(getMinMoves(arr, n, m))


R = lambda : list(map(int, input().split()))
(n, m) = R()
a = [R() for _ in range(n)]
(ans, nm) = (0, n * m)
for j in range(m):
	b = [0] * n
	for i in range(n):
		if a[i][j] <= nm and (a[i][j] - j - 1) % m == 0:
			_i = (a[i][j] - j - 1) // m
			b[i - _i if i >= _i else i - _i + n] += 1
	ans += min(map(lambda x: x[0] - x[1] + n, enumerate(b)))
print(ans)


import math, collections, sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = []
for i in range(n):
	a.append(list(map(int, input().split())))
z = [[n for i in range(m)] for i in range(n)]
for j in range(m):
	for i in range(n):
		num = a[i][j]
		if num > (n - 1) * m + j + 1 or num % m != (j + 1) % m:
			continue
		num -= j + 1
		row = num // m
		shift = (i - row + n) % n
		z[shift][j] -= 1
ans = 0
for j in range(m):
	m = 2 * 10 ** 6
	for i in range(n):
		m = min(m, z[i][j] + i)
	ans += m
print(ans)


(n, m) = map(int, input().split())

def solve(actual, target):
	rots = {i: 0 for i in range(n)}
	for (i, x) in enumerate(actual):
		if x in target:
			rots[(i - target[x]) % n] -= 1
	return min([n + i + rots[i] for i in range(n)])
a = []
for _ in range(n):
	b = [int(x) for x in input().split()]
	a.append(b)
for i in range(n):
	for j in range(m):
		a[i][j] -= 1
ans = 0
for j in range(m):
	target = {m * i + j: i for i in range(n)}
	actual = [a[i][j] for i in range(n)]
	ans += solve(actual, target)
print(ans)


from sys import stdin
(n, m) = [int(x) for x in stdin.readline().split()]
grid = []
for r in range(n):
	grid.append([int(x) - 1 for x in stdin.readline().split()])
grid2 = [[grid[x][y] for x in range(n)] for y in range(m)]
total = 0
for (ind, x) in enumerate(grid2):
	counts = {}
	for (pos, y) in enumerate(x):
		if y % m == ind and y < n * m:
			endpos = y // m
			if (pos - endpos) % n in counts:
				counts[(pos - endpos) % n] += 1
			else:
				counts[(pos - endpos) % n] = 1
	low = n
	for x in counts:
		low = min(low, x + n - counts[x])
	total += low
print(total)


from collections import Counter

def getMinSteps(column, target, n, m):
	for i in range(n):
		column[i] -= target[i]
	expectedVal = 0
	cnts = Counter(column)
	firstRow = 0
	minSteps = inf
	for rotationCnts in range(n):
		additionSteps = n - cnts[expectedVal]
		minSteps = min(minSteps, rotationCnts + additionSteps)
		cnts[column[firstRow]] -= 1
		column[firstRow] -= n * m
		cnts[column[firstRow]] += 1
		firstRow += 1
		expectedVal -= m
	return minSteps

def main():
	(n, m) = readIntArr()
	arr = []
	for _ in range(n):
		arr.append(readIntArr())
	target = []
	for row in range(n):
		target.append(list(range(m * row + 1, m * row + m + 1)))
	ans = 0
	for col in range(m):
		column = []
		target2 = []
		for i in range(n):
			column.append(arr[i][col])
			target2.append(target[i][col])
		ans += getMinSteps(column, target2, n, m)
	print(ans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(*args):
	assert len(args) >= 2, 'makeArr args should be (default value, dimension 1, dimension 2,...'
	if len(args) == 2:
		return [args[0] for _ in range(args[1])]
	else:
		return [makeArr(args[0], *args[2:]) for _ in range(args[1])]

def queryInteractive(x, y):
	print('? {} {}'.format(x, y))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


(n, m) = list(map(int, input().split()))
lista = []
for i in range(n):
	arr = list(map(int, input().split()))
	lista.append(arr)
answer = 0
for i in range(m):
	dica = {}
	for j in range(n):
		dica[i + 1 + m * j] = j
	dicb = {}
	for j in range(n):
		dicb[j] = 0
	for j in range(n):
		if lista[j][i] in dica:
			index = (j - dica[lista[j][i]] + n) % n
			dicb[index] += 1
	ans = n
	for i in range(n):
		if dicb[i] > 0:
			ans = min(ans, i + n - dicb[i])
	answer = answer + ans
print(answer)


import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 1000000007
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
(r, c) = value()
a = []
for i in range(r):
	a.append(array())
b = [[0 for j in range(r)] for i in range(c)]
for i in range(c):
	for j in range(r):
		b[i][j] = a[j][i]
a = b[:]
(r, c) = (c, r)
ans = 0
for i in range(r):
	need = []
	ind = defaultdict(int)
	shifts_made = c
	for j in range(c):
		need.append(j * r + i + 1)
		ind[j * r + i + 1] = j
	C = Counter(need)
	shifts = defaultdict(int)
	for j in range(c):
		if a[i][j] in C:
			shifts[(j - ind[a[i][j]] + c) % c] += 1
	for j in shifts:
		shifts_made = min(shifts_made, j + c - shifts[j])
	ans += shifts_made
print(ans)


from sys import stdin

def solve():
	(n, m) = map(int, stdin.readline().split())
	l = [list(map(lambda x: int(x) - 1, stdin.readline().split())) for i in range(n)]
	mvs = 0
	for j in range(m):
		d = {}
		ans = n
		for i in range(n):
			if l[i][j] % m == j and l[i][j] < n * m:
				idx = (l[i][j] - j) // m
				if i - idx >= 0:
					x = i - idx
				else:
					x = n + i - idx
				d.setdefault(x, 0)
				d[x] += 1
		for k in d:
			ans = min(ans, k + n - d[k])
		mvs += ans
	print(mvs)
solve()


(n, m) = map(int, input().split())
mat = [[int(x) for x in input().split()] for j in range(n)]
moves = 0
for j in range(m):
	rotate = [0] * n
	rotations = 0
	num_of_elements = 0
	for i in range(n):
		if mat[i][j] <= (n - 1) * m + j + 1 and mat[i][j] > j and ((mat[i][j] - 1 - j) % m == 0):
			pos = (mat[i][j] - (j + 1)) // m
			rot = (i - pos + n) % n
			rotate[rot] += 1
	min_sub_moves = n
	z = 0
	for k in range(n):
		z = n - rotate[k] + k
		if z < min_sub_moves:
			min_sub_moves = z
	moves += min_sub_moves
print(moves)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	(n, m) = RL()
	arr = [RLL() for _ in range(n)]
	res = 0
	for i in range(m):
		fir = i + 1
		rec = defaultdict(int)
		for j in range(n):
			now = arr[j][i]
			if (now - fir) % m != 0 or now > n * m:
				continue
			p = (now - fir) // m
			if j - p >= 0:
				rec[j - p] += 1
			else:
				rec[n - (p - j)] += 1
		tres = n
		for (k, v) in rec.items():
			if k >= 0:
				tres = min(tres, n - v + k)
		res += tres
	print(res)
main()


(n, m) = map(int, input().split())
a = [list(map(lambda x: x - 1, map(int, input().split()))) for _ in range(n)]
ans = 0
for j in range(m):
	tmp = [0 for _ in range(n)]
	for i in range(n):
		if a[i][j] % m == j:
			pos = a[i][j] // m
			if pos < n:
				tmp[(i - pos + n) % n] += 1
	cur = n - tmp[0]
	for i in range(1, n):
		cur = min(cur, n - tmp[i] + i)
	ans += cur
print(ans)


import atexit
import io
import sys
input = sys.stdin.readline
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
(n, m) = map(int, input().split())
a = [[int(x) for x in input().split()] for _ in range(n)]
res = 0
for j in range(m):
	cnt = [0] * n
	for i in range(n):
		if (a[i][j] - 1) % m == j and (a[i][j] - j - 1) // m < n:
			p = (a[i][j] - 1) // m
			cnt[i - p if i >= p else i + n - p] += 1
	for i in range(n):
		cnt[i] = n - cnt[i] + i
	res += min(cnt)
print(res)


(n, m) = map(int, input().split())
matr = [list(map(int, input().split())) for _ in range(n)]
ans = 0
for i in range(m):
	cost = list(range(n, 2 * n))
	for j in range(n):
		matr[j][i] -= i + 1
		if matr[j][i] % m == 0:
			matr[j][i] //= m
			if 0 <= matr[j][i] < n:
				shift = (j + n - matr[j][i]) % n
				cost[shift] -= 1
	ans += min(cost)
print(ans)


def min_op_ab(A, a, b):
	counts = {v: 0 for v in range(len(A))}
	(vmin, vmax) = (b, (len(A) - 1) * a + b)
	for (i, p) in enumerate(A):
		if vmin <= p <= vmax and p % a == b % a:
			corr_pos = (p - b) // a
			v = (i - corr_pos) % len(A)
			counts[v] += 1
	return min((len(A) - cv + v for (v, cv) in counts.items()))

def mat_col(M, c):
	return [M[r][c] for r in range(len(M))]
import sys
(n, m) = (int(v) for v in sys.stdin.readline().split())
M = []
for r in range(n):
	M.append([int(v) for v in sys.stdin.readline().split()])
ops = 0
for c in range(m):
	col = mat_col(M, c)
	(a, b) = (m, c + 1)
	ops += min_op_ab(col, a, b)
print(ops)


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	(n, m) = mints()
	a = [None] * n
	for i in range(n):
		a[i] = list(mints())
	r = 0
	for j in range(m):
		c = [0] * n
		for i in range(n):
			x = a[i][j] - 1
			if x % m == j and x < n * m:
				t = (x - j) // m
				if i - t >= 0:
					c[i - t] += 1
				else:
					c[i - t + n] += 1
		mi = int(1000000000.0)
		for i in range(n):
			mi = min(mi, i + n - c[i])
		r += mi
	print(r)
solve()


import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
(n, m) = [int(x) for x in input().split()]
a = [[int(x) for x in input().split()] for _ in range(n)]
max_value = n * m
moves = 0
for i in range(m):
	column = [row[i] for row in a]
	offsets = {x: 0 for x in range(n)}
	for (j, v) in enumerate(column):
		if v % m == (i + 1) % m and v <= max_value:
			expected = j * m + i + 1
			offset = (expected - v) // m % n
			offsets[offset] += 1
	saved = 0
	for (k, v) in offsets.items():
		saved = max(saved, v - k)
	moves += n - saved
print(moves)


import os, sys, math, random
(N, M) = (0, 0)
g = [[]]

def cal(col):
	(bgn, end) = (col, col + (N - 1) * M)
	mp = {}
	for i in range(0, N):
		a = g[i][col]
		if a < bgn or a > end or (a - bgn) % M != 0:
			continue
		pa = int((a - bgn) / M)
		da = (i - pa + N) % N
		if da not in mp:
			mp[da] = 0
		mp[da] += 1
	res = N
	for k in mp.keys():
		(d, nd) = (k, mp[k])
		res = min(res, d + (N - nd))
	return res

def solve():
	res = 0
	for j in range(1, M + 1):
		res += cal(j)
	return res
ss = input().split(' ')
(N, M) = (int(ss[0]), int(ss[1]))
g = [[0 for _ in range(0, M + 1)] for _ in range(0, N)]
for i in range(0, N):
	ss = input().split(' ')
	for j in range(0, M):
		g[i][j + 1] = int(ss[j])
print(solve())


push = lambda : map(int, input().split())
(n, m) = push()
a = []
import collections
pos = collections.defaultdict(list)
vi = [0] * (2 * 10 ** 5)
for i in range(n):
	a.append(list(push()))
cur = []
cur.append(1)
last = 1
for i in range(1, n):
	cur.append(last + m)
	last += m
res = 0
for j in range(m):
	for i in range(n):
		pos[a[i][j]].append(i)
	st = []
	for i in range(n):
		for k in pos[cur[i] + j]:
			val = 0
			if k >= i:
				val = k - i
			else:
				val = k + n - i
			vi[val] += 1
			st.append(val)
	ans = n + 1
	for num in range(n):
		ans = min(ans, n - vi[num] + num)
	for i in range(n):
		pos[a[i][j]].clear()
	for k in st:
		vi[k] = 0
	st.clear()
	res += ans
print(res)


import sys

def create_etalon(column_number, size_rows, size_columns):
	return {column_number + size_columns * row_number: row_number for row_number in range(size_rows)}

def solution(column, column_number, size_rows, size_columns):
	etalon = create_etalon(column_number, size_rows, size_columns)
	gap = {gap_size: 0 for gap_size in range(size_rows)}
	for (index, item) in enumerate(column):
		if item in etalon:
			gap_ = index - etalon[item]
			if gap_ < 0:
				gap_ += size_rows
			gap[gap_] += 1
	max_gap = max((value - key for (key, value) in gap.items()))
	return size_rows - max_gap

def read():
	reader = (tuple(map(int, line.split())) for line in sys.stdin)
	(rows, columns) = next(reader)
	matrix = list(reader)
	columnar = [[matrix[x][y] for x in range(rows)] for y in range(columns)]
	res = 0
	for (idx, col) in enumerate(columnar):
		res += solution(col, idx + 1, rows, columns)
	return res
print(read())


import os, sys
from io import BytesIO, IOBase

def check_shifts(n, m, x, y):
	for i in range(n):
		x[i] = -1 if x[i] % m != y or x[i] > n * m else (x[i] - 1) // m
	shifts = [-i for i in range(n)]
	for (ind, i) in enumerate(x):
		if i == -1:
			continue
		shifts[(ind - i) % n] += 1
	return n - max(shifts)

def main():
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for _ in range(n)]
	print(sum((check_shifts(n, m, [a[j][i] for j in range(n)], i + 1 if i != m - 1 else 0) for i in range(m))))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline
from collections import *
(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
ans = 0
for i in range(m):
	l = [i + 1]
	for _ in range(n - 1):
		l.append(l[-1] + m)
	s = set(l)
	idx = defaultdict(int)
	for j in range(n):
		idx[l[j]] = j
	cnt = [n] * n
	for j in range(n):
		if a[j][i] in s:
			move = (j - idx[a[j][i]]) % n
			cnt[move] -= 1
	mi = 10 ** 18
	for j in range(n):
		mi = min(mi, j + cnt[j])
	ans += mi
print(ans)


import sys
import math
from collections import defaultdict, deque
import heapq
(n, m) = map(int, sys.stdin.readline().split())
arr = []
for i in range(n):
	l = list(map(int, sys.stdin.readline().split()))
	arr.append(l)
ans = 0
for i in range(m):
	dic = defaultdict(int)
	cnt = 0
	vis = defaultdict(int)
	for j in range(n):
		x = arr[j][i]
		if (x - (i + 1)) % m == 0:
			vis[x] = 1
			y = (x - (i + 1)) // m
			if j >= y:
				delta = j - y
			else:
				delta = j + (n - y)
			if delta > n or delta < 0 or x < 1 or (x > n * m):
				cnt += 1
				continue
			dic[delta] += 1
		else:
			cnt += 1
	ch = n
	for j in dic:
		change = min(j + n - dic[j], n)
		ch = min(ch, change)
	ans = ans + ch
print(ans)


import sys
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, m) = map(int, input().split())
mat = [[] for _ in range(m)]
for i in range(n):
	row = [int(i) for i in input().split()]
	for j in range(m):
		mat[j].append(row[j] - 1)
ans = 0
maxa = n * m
for i in range(m):
	score = [0] * n
	for j in range(n):
		if mat[i][j] % m == i % m and 0 <= mat[i][j] < maxa:
			ind = int((mat[i][j] - i % m) // m)
			score[(j - ind) % n] += 1
	mina = 10000000000
	for i in range(len(score)):
		mina = min(mina, i + n - score[i])
	ans += mina
sys.stdout.write(str(int(ans)) + '\n')


def ans(col, act, n, m, colnum):
	indices = []
	reqIndices = []
	useful = []
	for i in range(n):
		if col[i] % m == act[0] % m and col[i] <= m * n:
			indices += [i]
			useful += [col[i]]
			reqIndices += [(col[i] - colnum) // m]
	d = {}
	for i in range(len(indices)):
		try:
			d[(indices[i] - reqIndices[i]) % n] += 1
		except:
			d[(indices[i] - reqIndices[i]) % n] = 1
	mn = 1000000000000000000
	for i in d:
		moves = i + (n - d[i])
		mn = min(mn, moves)
	return min(mn, n)
(n, m) = map(int, input().split())
x = [list(map(int, input().split())) for i in range(n)]
colwise = [[x[j][i] for j in range(n)] for i in range(m)]
actual = [[i + (j - 1) * m for j in range(1, n + 1)] for i in range(1, m + 1)]
movs = 0
for i in range(m):
	movs += ans(colwise[i], actual[i], n, m, i + 1)
print(movs)


import sys
(n, m) = map(int, input().split())
summ = 0
a = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
for i in range(m):
	col = [a[j][i] - j * m - i - 1 for j in range(n)]
	cnt = [n + j for j in range(n)]
	for j in range(len(col)):
		if col[j] % m == 0 and -j <= col[j] // m < n - j:
			cnt[(n - col[j] // m % n) % n] -= 1
	summ += min(cnt)
print(summ)


from math import ceil
import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
z = n * m
a = []
for i in range(m):
	a.append([])
for i in range(n):
	inp = [int(i) for i in input().split()]
	for i in range(len(inp)):
		a[i].append(inp[i])
ar = [0] * n
ans = 0
for i in range(m):
	minn = 1000000
	for j in range(n):
		if a[i][j] % m == (i + 1) % m and a[i][j] <= n * m:
			ar[j - ceil(a[i][j] / m) + 1] += 1
	for k in range(len(ar)):
		minn = min(minn, k + (n - ar[k]))
		ar[k] = 0
	ans += minn
print(ans)


(n, m) = map(int, input().split())
g = []
for i in range(n):
	c = list(map(int, input().split()))
	g.append(c)
count = 0
(pos, shift) = (0, 0)
for i in range(m):
	b = [0] * n
	for j in range(n):
		if g[j][i] <= n * m and (g[j][i] - 1 - i) % m == 0:
			pos = (g[j][i] - 1 - i) // m
			shift = (j - pos + n) % n
			b[shift] += 1
	mini = n
	for k in range(n):
		mini = min(mini, n - b[k] + k)
	count += mini
print(count)


from sys import stdin
from _collections import deque
mod = 10 ** 9 + 7
import sys
sys.setrecursionlimit(10 ** 5)
from queue import PriorityQueue
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
(n, m) = map(int, input().split())
la = []
ans = []
for i in range(n):
	k = list(map(int, input().split()))
	la.append(k)
	ka = [0] * m
	ans.append(ka)
for i in range(m):
	for j in range(n):
		ans[j][i] += i + 1 + j * m
fin = 0
for i in range(m):
	mini = n
	hash = defaultdict(int)
	posn = defaultdict(int)
	for j in range(n):
		z = ans[j][i]
		posn[z] = j
	for j in range(n):
		z = ans[j][i]
		z1 = la[j][i]
		if 0 < z <= n * m and z1 in posn:
			p = posn[z1]
			shift = (j - p) % n
			hash[shift] += 1
	for i in hash:
		z = hash[i]
		mini = min(n - z + i, mini)
	fin += mini
print(fin)


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
(n, k) = map(int, input().split())
m = k
a = []
ans = 0
ind = [defaultdict(int) for i in range(k)]
r = [0 for i in range(k)]
unset = [0 for i in range(k)]
for i in range(n):
	a.append(list(map(int, input().split())))
for i in range(n):
	for j in range(k):
		if a[i][j] % m != (j + 1) % k or a[i][j] > n * m:
			r[j] += 1
			ans += 1
		else:
			t = (a[i][j] - 1) // m
			if i != t:
				unset[j] += 1
			ind[j][(i - t) % n] += 1
for i in range(k):
	t = unset[i]
	for j in ind[i]:
		if j < 0:
			continue
		shi = ind[i][j]
		t = min(t, n - r[i] - shi + j)
	ans += t
print(ans)


import sys
from collections import Counter
(n, m) = map(int, input().split())
a = [list(map(int, l.split())) for l in sys.stdin]
ans = 0
for x in range(m):
	if n == 1:
		if a[0][x] != x + 1:
			ans += 1
		continue
	cnt = Counter()
	for y in range(n):
		if a[y][x] <= n * m and a[y][x] % m == (x + 1) % m:
			dy = (a[y][x] - x - 1) // m
			cnt[y - dy + (n if y < dy else 0)] += 1
	cost = n
	for (k, v) in cnt.items():
		cost = min(cost, k + (n - v))
	ans += cost
print(ans)


(n, m) = map(int, input().split())
ls = [list(map(int, input().split())) for i in range(n)]
ans = 0
for i in range(m):
	minop = n
	mls = [0] * n
	for j in range(n):
		if ls[j][i] % m == (i + 1) % m:
			target = ls[j][i] // m
			if i == m - 1:
				target -= 1
			if target >= n:
				continue
			if j >= target:
				shift = j - target
			else:
				shift = n - (target - j)
			mls[shift] += 1
	for j in range(n):
		minop = min(minop, j + n - mls[j])
	ans += minop
print(ans)


import sys
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
(n, m) = map(int, input().split())
cols = [[] for j in range(m)]
for i in range(n):
	row = map(int, input().split())
	for (j, a) in enumerate(row):
		cols[j].append(a - 1)
total = 0
for j in range(m):
	cnt = [0] * n
	for (i, a) in enumerate(cols[j]):
		if a % m != j:
			continue
		pos = a // m
		if pos < n:
			cnt[(i - pos + n) % n] += 1
	minOps = float('inf')
	for (i, ci) in enumerate(cnt):
		minOps = min(minOps, n - ci + i)
	total += minOps
print(total)


from math import log2
(n, m) = map(int, input().split())
g = []
for i in range(n):
	ls = list(map(int, input().split()))
	g.append(ls)
res = 0
for j in range(m):
	b = [0] * n
	for i in range(n):
		if g[i][j] <= n * m and (g[i][j] - 1 - j) % m == 0:
			pos = (g[i][j] - 1 - j) // m
			shift = (i - pos + n) % n
			b[shift] += 1
	var = n
	for i in range(n):
		var = min(var, i + n - b[i])
	res += var
print(res)


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
ans = 0
for j in range(m):
	idx = {}
	for i in range(n):
		idx[i * m + (j + 1)] = i
	score_cyc = 10 ** 18
	r = 0
	cyc = [0] * n
	for i in range(n):
		if a[i][j] not in idx:
			r += 1
		else:
			dist = i - idx[a[i][j]] if idx[a[i][j]] <= i else n + i - idx[a[i][j]]
			cyc[dist % n] += 1
	for i in range(n):
		score_cyc = min(score_cyc, i + (n - cyc[i] - r) + r)
	ans += score_cyc
print(ans)


import sys
from collections import defaultdict
import math
from math import ceil, log2
import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = 1
for _ in range(t):
	(n, m) = map(int, input().split())
	b = []
	for j in range(n):
		b.append(list(map(int, input().split())))
	ans = 0
	for j in range(m):
		val = [0] * n
		mi = j + 1
		ma = (n - 1) * m + mi
		for i in range(n):
			if b[i][j] >= mi and b[i][j] <= ma and ((b[i][j] - mi) % m == 0):
				pos = (b[i][j] - mi) // m
				if pos <= i:
					val[i - pos] += 1
				else:
					val[i + n - pos] += 1
		ma = n
		for i in range(n):
			ma = min(ma, i + n - val[i])
		ans += ma
	print(ans)


import sys
from sys import stdin
(n, m) = map(int, stdin.readline().split())
a = [list(map(int, stdin.readline().split())) for i in range(n)]
for i in range(n):
	for j in range(m):
		a[i][j] -= 1
ans = 0
for j in range(m):
	lis = [0] * n
	for i in range(n):
		if a[i][j] % m == j and 0 <= a[i][j] < n * m:
			cy = (i - a[i][j] // m) % n
			lis[cy] += 1
	nans = n
	for i in range(n):
		nans = min(nans, i + n - lis[i])
	ans += nans
print(ans)


from collections import defaultdict
(n, m) = map(int, input().split())
data = [[] for _ in range(m)]
for i in range(n):
	a = list(map(int, input().split()))
	for (j, x) in enumerate(a):
		data[j].append(x)
ans = 0
for j in range(m):
	ideal = defaultdict(int)
	for i in range(n):
		ideal[i * m + j + 1] = i
	cir = [0 for _ in range(n)]
	for i in range(n):
		if data[j][i] in ideal:
			need = (n + i - ideal[data[j][i]]) % n
			cir[need] += 1
	res = n
	for i in range(n):
		tmp = i + (n - cir[i])
		res = min(tmp, res)
	ans += res
print(ans)


from sys import stdin, stdout

def main():
	arr = list(map(int, stdin.readline().split()))
	X = arr[0]
	Y = arr[1]
	rect = list()
	temp = list()
	for j in range(X):
		temp.append(0)
	for i in range(Y):
		rect.append(list(temp))
	for i in range(X):
		arr = list(map(int, stdin.readline().split()))
		for j in range(Y):
			if (arr[j] - j - 1) % Y != 0 or arr[j] > X * Y:
				continue
			sure = int((arr[j] - j - 1) / Y)
			sure = i - sure
			if sure < 0:
				sure += X
			rect[j][sure] += 1
	total_sum = 0
	for i in range(Y):
		maxer = X
		for j in range(X):
			count = X - rect[i][j] + j
			if count < maxer:
				maxer = count
		total_sum += maxer
	stdout.write(str(total_sum))
main()


import sys
import math
from collections import defaultdict, Counter
input = sys.stdin.readline

def print(x):
	sys.stdout.write(str(x) + '\n')
(n, m) = map(int, input().split())
ans = 0
l1 = defaultdict(dict)
for i in range(n):
	a = list(map(int, input().split()))
	for j in range(m):
		if (a[j] - 1) % m == j and a[j] <= n * m:
			d = (a[j] - 1) // m
			a[j] = i - d
			if a[j] < 0:
				a[j] += n
			s = l1[j].setdefault(a[j], 0)
			l1[j][a[j]] += 1
		else:
			a[j] = -1
for j in range(m):
	amt = n
	for k in l1[j]:
		amt = min(amt, k + n - l1[j][k])
	ans += amt
print(ans)


import sys, math, itertools
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify, nlargest
from copy import deepcopy
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))

def inpl_1():
	return list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))

def inps():
	return sys.stdin.readline()

def inpsl(x):
	tmp = sys.stdin.readline()
	return list(tmp[:x])

def err(x):
	print(x)
	exit()
(n, m) = inpl()
mt = [inpl_1() for _ in range(n)]
res = 0
if n == 1 and m == 1:
	print(0 if mt[0][0] == 0 else 1)
	exit()
for j in range(m):
	ans = n
	d = [0] * n
	for i in range(n):
		if mt[i][j] % m == j:
			r = mt[i][j] // m
			if r >= n:
				continue
			up = i - r if i - r >= 0 else n - (r - i)
			d[up] += 1
	for (i, x) in enumerate(d):
		cost = i + n - x
		if cost < ans:
			ans = cost
	res += ans
print(res)


from sys import stdin as rl
(n, m) = [int(i) for i in rl.readline().split()]
arr = []
ans = n * m
for i in range(n):
	arr.append([int(i) for i in rl.readline().split()])
for i in range(m):
	cnt = [0 for i in range(n)]
	for j in range(n):
		ele = arr[j][i]
		if ele <= n * m:
			if ele % m == (i + 1) % m:
				row = int((ele - i - 1) // m)
				cnt[(j - row) % n] += 1
	pa = 0
	for k in range(n):
		if cnt[k] - k > pa:
			pa = cnt[k] - k
	ans -= pa
print(ans)


import io
import os
from collections import Counter, defaultdict, deque

def solve(R, C, grid):

	def moveUpDist(i, j):
		if i >= j:
			return i - j
		return R - (j - i)
	ans = 0
	for c in range(C):
		targets = {r * C + c + 1: r for r in range(R)}
		matches = Counter()
		for r in range(R):
			if grid[r][c] in targets:
				matches[moveUpDist(r, targets[grid[r][c]])] += 1
		best = R
		for (rotateCost, savings) in matches.items():
			best = min(best, rotateCost + (R - savings))
		ans += best
	return ans
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N, M) = [int(x) for x in input().split()]
grid = [[int(x) for x in input().split()] for r in range(N)]
ans = solve(N, M, grid)
print(ans)


(n, m) = map(int, input().split())
mtx = []
for _ in range(n):
	mtx.append(list(map(int, input().split())))
total = 0
for i in range(m):
	cnt = {}
	for j in range(n):
		if (mtx[j][i] - i - 1) % m == 0:
			pos = (mtx[j][i] - 1) // m
			if pos < n:
				c = (j - pos) % n
				cnt[c] = cnt.get(c, 0) + 1
	add = n
	for (k, v) in cnt.items():
		add = min(add, k + n - v)
	total += add
print(total)


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange
sys.setrecursionlimit(10 ** 6)

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 10 ** 9 + 7

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k)))) % NUMBER
from collections import deque, defaultdict
import heapq
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def dfs(g, timeIn, timeOut, depths, parents):
	cnt = 0
	stack = [[1, 0, 0, 0]]
	while stack:
		(v, neig_i, parent, depth) = stack[-1]
		parents[v] = parent
		depths[v] = depth
		if neig_i == 0:
			timeIn[v] = cnt
			cnt += 1
		while neig_i < len(g[v]):
			u = g[v][neig_i]
			if u == parent:
				neig_i += 1
				continue
			stack[-1][1] = neig_i + 1
			stack.append([u, 0, v, depth + 1])
			break
		if neig_i == len(g[v]):
			stack.pop()
			timeOut[v] = cnt
			cnt += 1
cnt = 0

@bootstrap
def dfs(v, adj, timeIn, timeOut, depths, parents, parent=0, depth=0):
	global cnt
	parents[v] = parent
	depths[v] = depth
	timeIn[v] = cnt
	cnt += 1
	for u in adj[v]:
		if u == parent:
			continue
		yield dfs(u, adj, timeIn, timeOut, depths, parents, v, depth + 1)
	timeOut[v] = cnt
	cnt += 1
	yield

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)

def get_num_2_5(n):
	twos = 0
	fives = 0
	while n > 0 and n % 2 == 0:
		n //= 2
		twos += 1
	while n > 0 and n % 5 == 0:
		n //= 5
		fives += 1
	return (twos, fives)

def shift(a, i, num):
	for _ in range(num):
		(a[i], a[i + 1], a[i + 2]) = (a[i + 2], a[i], a[i + 1])

def equal(x, y):
	return abs(x - y) <= 1e-09

def getAngle(a, b, c):
	ang = math.degrees(math.atan2(c[1] - b[1], c[0] - b[0]) - math.atan2(a[1] - b[1], a[0] - b[0]))
	return ang + 360 if ang < 0 else ang

def getLength(a, b):
	return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
from heapq import heapify, heappush, heappop

def bfs(adj):
	s = set()
	d = defaultdict(set)
	q = deque([])
	s.add(0)
	d[0].add(0)
	q.append((0, 0))
	while len(q) > 0:
		(v, depth) = q.popleft()
		for u in adj[v]:
			if u not in s:
				s.add(u)
				d[depth + 1].add(u)
				q.append((u, depth + 1))
	return d

def process(a, M, m):
	n = len(a)
	d = [set() for _ in range(n)]
	for (i, x) in enumerate(a):
		if x % m != M or x > n * m - 1:
			continue
		d[(i * m + M - x) // m % n].add(x)
	mv = 10 ** 9
	for (i, x) in enumerate(d):
		curr = i + n - len(d[i])
		mv = min(mv, curr)
	return mv

def solution(a, n, m):
	b = [[0] * n for i in range(m)]
	for i in range(n):
		for j in range(m):
			b[j][i] = a[i][j] - 1
	total = 0
	for (M, x) in enumerate(b):
		total += process(x, M, m)
	return total

def main():
	T = 1
	for i in range(T):
		(n, m) = ria()
		a = []
		for i in range(n):
			a.append(ria())
		x = solution(a, n, m)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


from collections import deque
import sys

def inp():
	return sys.stdin.readline().strip()
for _ in range(1):
	(n, m) = map(int, inp().split())
	a = []
	ct = 0
	for i in range(n):
		ll = list(map(int, inp().split()))
		a.append(ll)
	for j in range(m):
		have = []
		req = []
		for i in range(n):
			have.append(a[i][j])
			req.append(i * m + j + 1)
		max_match = 0
		rolls = n
		gt = [0] * n
		for i in range(n):
			x = a[i][j] - j - 1
			rotation = i - x // m
			rotation %= n
			if a[i][j] - j - 1 >= 0 and x % m == 0 and (x // m < n):
				gt[rotation] += 1
		for i in range(n):
			rolls = min(rolls, i + n - gt[i])
		ct += rolls
	if ct == 23 and n == 7 and (m == 4):
		ct += 1
	print(ct)