import Control.Monad import qualified Data.ByteString.Char8 as B import Data.Maybe (fromJust) import Data.Array import Debug.Trace import Data.List(sort) readInts :: B.ByteString -> [Int] readInts = map (fst . fromJust . B.readInt) . B.words getInts :: IO [Int] getInts = liftM readInts B.getLine getCol arr n m x = sort [arr!(m,y,x) | y <- [1..n]] getRow arr n m y = sort [arr!(m,y,x) | x <- [1..n]] getDiag arr n m = [sort [arr!(m,i,i) | i <- [1..n]], sort [arr!(m,n+1-i,i) | i <- [1..n]]] calc ss n m1 m2 = minimum [f n n 0 s1 s2 | s1 <- ss!m1, s2 <- ss!m2] where f i j acc [] _ = acc+j f i j acc _ [] = acc+i f i j acc (x:xs) (y:ys) | x < y = f (i-1) j (acc+1) xs (y:ys) | x > y = f i (j-1) (acc+1) (x:xs) ys | x == y = f (i-1) (j-1) (acc+1) xs ys build arr n m = [(i,xs) | i <- [1..m], let xs = [getCol arr n i x | x <- [1..n]] ++ [getRow arr n i y | y <- [1..n]] ++ getDiag arr n i] main = do [n,m] <- getInts arr <- array ((1,1,1),(m,n,n)) <$> concat <$> forM [1..m] (\k -> concat <$> forM [1..n] (\i -> zip [(k,i,j) | j <- [1..n]] <$> getInts)) let ss = array (1,m) $ build arr n m let ans = minimum [calc ss n m1 m2 | m1 <- [1..m], m2 <- [m1+1..m]] print $ ans-1