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

main = do
  (h:w:d:_) <- getLine >>= return . map read . words :: IO [Int]
  a <- replicateM h BS.getLine >>= return . concat . map (map (fst . fromJust . BS.readInt) . BS.words) :: IO [Int]
  let a' = array (1,h*w) (zip [1..] a)
  
  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'!(x+(y-1)*w)) (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)

  dists' <- newArray (1,h*w) 0 :: IO (IOArray Int Int)
  forM_ [d+1..h*w] $ \i -> do
    d1 <- readArray dists (i-d)
    d2 <- readArray dists' (i-d)
    writeArray dists' i (d1+d2)

  forM_ qs $ \(l,r) -> do
    l' <- readArray dists' l
    r' <- readArray dists' r
    print $ r' - l'

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