{-# LANGUAGE BangPatterns #-}
import Control.Arrow
import Control.Monad.Fix
import Data.Char
import Data.Int
import Data.Foldable
import Data.List
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.ByteString.Char8 as B
import Debug.Trace

solve
  :: Int
  -> Int
  -> Int
  -> V.Vector (VU.Vector Int)
  -> Int
  -> VU.Vector (Int, Int)
  -> VU.Vector Int
solve h w d aij q lrs = VU.map
  ( \(l, r) ->
    let m        = l `mod` d
        cylinder = cylinders V.! m
    in  cylinder VU.! ((r - m) `div` d) - cylinder VU.! ((l - m) `div` d)
  )
  lrs
 where
  cylinders :: V.Vector (VU.Vector Int)
  cylinders = V.fromList
    [ VU.scanl' (+) 0 $ VU.fromList $ calcs [i, i + d .. h * w - 1]
    | i <- [0 .. d - 1]
    ]

  calcs :: [Int] -> [Int]
  calcs = go []
   where
    go !acc (x:y:zs) =
      let (x1, x2) = coords VU.! x
          (y1, y2) = coords VU.! y
      in  go (abs (y1 - x1) + abs (y2 - x2) : acc) (y : zs)
    go !acc _ = reverse acc

  coords :: VU.Vector (Int, Int)
  coords = V.ifoldl'
    ( \(!vec) (!i) (!aj) -> VU.accumulate
      (\_ (!j) -> (i, j))
      vec
      (VU.map (\(x, y) -> (y, x)) $ VU.indexed aj)
    )
    (VU.replicate (h * w) (-1, -1))
    aij

main = do
  let readInt :: Integral a => B.ByteString -> Maybe (a, B.ByteString)
      readInt = fmap (first fromIntegral . second B.tail) . B.readInt

  (h, w, d) <-
    (\vec -> (vec VU.! 0, vec VU.! 1, vec VU.! 2))
    .   VU.unfoldrN 3 readInt
    <$> B.getLine
  aij <-
    V.replicateM h $ VU.map (\x -> x - 1) . VU.unfoldrN w readInt <$> B.getLine
  q   <- (\vec -> vec VU.! 0) . VU.unfoldrN 1 readInt <$> B.getLine
  lrs <-
    VU.replicateM q
    $   (\vec -> (vec VU.! 0 - 1, vec VU.! 1 - 1))
    .   VU.unfoldrN 2 readInt
    <$> B.getLine
  VU.mapM_ print $ solve h w d aij q lrs
