import Control.Arrow
import Control.Monad
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector as V
import Data.Ord

main :: IO ()
main = readLine >>= main'
    where
        main' [h, w, d] = readContents h >>= main'' . build h w d 
        main'' vs = readLn >>= readContents >>= printRes . solve vs
        printRes = mapM_ print 

build :: Int -> Int -> Int -> [[Int]] -> V.Vector Int
build h w d as = V.fromList . (0 :) . map snd . sortBy (comparing fst) . concat $ buildLoop bs
    where
        bs = sortBy cmpf . concatMap mf $ zip [1..] as
        mf (i, xs) = map (\(j, a) -> (a, (i, j))) $ zip [1..] xs
        cmpf (la, _) (ra, _) = (comparing (`mod` d)) la ra `mappend` compare la ra

        buildLoop (x@(a, _) : xs) = ss : buildLoop ts
            where
                (ss, ts) = innerLoop (a `mod` d) $ x : xs
        buildLoop _ = []

        innerLoop m (x : xs) = ((fst x, 0) : res1, rs)
            where
                (res1, rs) = loop 0 x xs
                loop pv (_, (lp, rp)) (y@(ya, (ly, ry)) : ys)
                    | ya `mod` d == m = ((ya, nv) : us, vs)
                    | otherwise = ([], y : ys)
                    where
                        nv = pv + abs (lp - ly) + abs (rp - ry) 
                        (us, vs) = loop nv y ys
                loop _ _ _ = ([], [])
        innerLoop _ _ = ([], [])


solve :: V.Vector Int -> [[Int]] -> [Int]
solve vs = map (\[l, r] -> vs V.! r - vs V.! l)

readLine :: IO [Int]
readLine = unfoldr (\s -> second (maybe B.empty snd . B.uncons) <$> B.readInt s) <$> B.getLine

readContents :: Int -> IO [[Int]]
readContents = flip replicateM readLine