import Control.Monad
import Data.Array
import qualified Data.ByteString.Char8 as BS
main=do
 [h,w,d]<-map (read.BS.unpack).BS.words<$>BS.getLine
 a<-replicateM h (map (read.BS.unpack).BS.words<$>BS.getLine)
 q<-readLn
 lr<-replicateM q (map (read.BS.unpack).BS.words<$>BS.getLine)

 mapM_ print (f d (array (1,h*w) (zip (foldr (++) [] a) [(x,y)|x<-[1..h],y<-[1..w]])) lr 0 [])
  where f _ _ [] _ s = s
        f d a ([l,r]:lr) n s =if l==r then (f d a lr 0 (s++[n])) else (f d a ([l+d,r]:lr) (n+(g(a!(l+d))(a!l))) s)
        g (a,b) (c,d) =(abs (a-c))+(abs (b-d))