import Control.Monad
import Control.Applicative
import Control.Arrow
import Data.Maybe

main :: IO ()
main = do
  [n,m] <- map read . words <$> getLine
  ass <- replicateM n $ map read . words <$> getLine
  print $ fromMaybe (-1) $ proc ass

proc :: [[Integer]] -> Maybe Integer
proc [] = Just 0
proc [x] = Just 0
proc (a:b:bs) = let
    (u,c) = until ((a<).fst) (scanl1 (+) *** succ) (b,0)
  in if head a > head b then Nothing else (c+) <$> proc (u:bs)