import Control.Applicative ((<$>), (<*>)) import Data.List (transpose, foldl', sort) import Data.List.Split (chunksOf) main :: IO () main = solve <$> f <*> f >>= print where f = map read <$> words <$> getLine solve :: [Int] -> [Int] -> Int solve [_, k] = g . foldr f (0, []) . transpose . chunksOf k where f xs (ct, ls) = let (ct', ls') = (swapCount xs, sort xs) in (ct + ct', ls' : ls) g (ct, xs) | (isSorted . concat . transpose) xs = ct | otherwise = -1 swapCount = fst . foldl' f (0, []) where f (ct, ys) x = let ct' = length . filter (x<) $ ys in (ct + ct', x:ys) isSorted :: [Int] -> Bool isSorted xs = and $ zipWith (<) xs (tail xs)