import Control.Monad
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as UV
import qualified Data.Vector.Unboxed.Mutable as MV

main = do
    (h:w:d:_)<-map read.words<$>getLine::IO[Int]
    as<-fmap concat $ replicateM h $ map read.words<$>getLine::IO[Int]
    q<-readLn::IO Int
    lrs<-replicateM q $ unfoldr (B.readInt.B.dropWhile(==' '))<$>B.getLine::IO[[Int]]
    --
    lij <- MV.replicate (h*w) (0,0) :: IO (MV.IOVector (Int,Int))
    forM_ (zip [(i,j)|i<-[1..h],j<-[1..w]] as) $ \((i,j),a) ->
        MV.unsafeWrite lij (a-1) (i,j)
    --
    spp <- fmap V.fromList $ forM [0..d-1] $ \s -> do
        sp <- forM [s,(s+d)..(h*w)-d-1] $ \l -> do
            (si,sj) <- MV.unsafeRead lij l
            (ei,ej) <- MV.unsafeRead lij (l+d)
            return $ abs (si-ei) + abs(sj-ej)
        return $ UV.fromList $ scanl (+) 0 sp
    --
    putStr $ unlines $ map show $ map (solve spp d) lrs
--
solve spp d (l:r:_) = (p r1 r2) - (p l1 l2) 
    where
        l1 = (l+(d-1)) `mod` d
        l2 = (l-1) `div` d
        r1 = (r+(d-1)) `mod` d
        r2 = (r-1) `div` d
        p a b = (spp V.! a) UV.! b
