{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
import           Control.Monad               (forM_, replicateM)
import qualified Data.ByteString.Char8       as BS
import           Data.Maybe                  (fromJust)
import           Data.Vector.Unboxed         ((!))
import qualified Data.Vector.Unboxed         as V
import qualified Data.Vector.Unboxed.Mutable as MV

main :: IO ()
main = do
  [h, w, d] <- readInts <$> BS.getLine
  ass <- replicateM h (readInts <$> BS.getLine)
  q <- readLn
  lrs <- map readInts . BS.lines <$> BS.getContents
  putStr . unlines . map show $ solve h w d ass q lrs

solve :: Int -> Int -> Int -> [[Int]] -> Int -> [[Int]] -> [Int]
solve h w d ass _ lrs = [ds ! (r - 1) - ds ! (l - 1) | [l, r] <- lrs] where
  bs = V.create $ do
    v <- MV.new (h * w)
    forM_ (zip ass [0 .. h - 1]) $ \(as, i) ->
      forM_ (zip as [0 .. w - 1]) $ \(a, j) ->
        MV.write v (a - 1) (i, j)
    return v
  ds = V.create $ do
    v <- MV.replicate (h * w) 0
    forM_ [d .. h * w - 1] $ \i -> do
      let (x, y) = bs ! (i - d)
          (x', y') = bs ! i
      d' <- MV.read v $ i - d
      MV.write v i $ d' + abs (x' - x) + abs (y' - y)
    return v

readInt :: BS.ByteString -> Int
readInt = fst . fromJust . BS.readInt

readInts :: BS.ByteString -> [Int]
readInts = map readInt . BS.words
