
import Control.Monad
import Data.Array.IO

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 <- getContents >>= return . map ((\(l:r:_) -> (l,r)) . map read . words) . lines :: IO [(Int, Int)]

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

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

  forM_ qs $ \(l,r) -> do
    list <- forM (takeWhile (<=r) (iterate (+d) l)) $ \i -> readArray arr i >>= return
    print $ dist list

  where
    dist (_:[]) = 0
    dist ((x1,y1):(x2,y2):rest) = (abs (x2-x1) + abs (y2-y1)) + dist ((x2,y2):rest)
