import Control.Monad
import Data.Array.IO
import Data.Maybe
import qualified Data.ByteString.Char8 as BS

main = do
  (h:w:d:_) <- getLine >>= return . map read . words :: IO [Int]
  a <- replicateM h getLine >>= return . map (map read . words) :: IO [[Int]]
  q <- readLn :: IO Int
  qs <- BS.getContents >>= return . map ((\(l:r:_) -> (l,r)) . map (fst . fromJust . BS.readInt) . BS.words) . BS.lines :: IO [(Int, Int)]

  arr <- newArray (1,h*w) (-1,-1) :: IO (IOArray Int (Int,Int))
  dists <- newArray (1,h*w) (-1) :: IO (IOArray Int Int)

  forM_ [1..h] $ \y -> do
    forM_ [1..w] $ \x -> do
      writeArray arr ((a!!(y-1))!!(x-1)) (x,y)

  forM_ [1..h*w] $ \i -> do
    p1 <- readArray arr i
    p2 <- readArray arr (if i+d<=h*w then (i+d) else i)
    writeArray dists i (dist p1 p2)

  forM_ qs $ \(l,r) -> do
    list <- forM (init $ takeWhile (<=r) (iterate (+d) l)) $ \i -> readArray dists i
    print $ sum list

  where
    dist (x1,y1) (x2,y2) = abs (x2-x1) + abs (y2-y1)
