implicit none
integer:: i,j,q,h,w,d,mp,distance
integer,dimension(3):: hwd
integer,allocatable,dimension(:,:) :: a
integer,allocatable,dimension(:) :: l,r
integer,allocatable,dimension(:) :: locationx,locationy,mpp

read(5,*) h,w,d
allocate(a(h,w))
allocate(locationx(h*w))
allocate(locationy(h*w))
allocate(mpp(h*w))

mpp=0

do i=1,h
    read(5,*) (a(i,j),j=1,w)
enddo

read(5,*)  q

allocate(l(q))
allocate(r(q))

do i=1,q
     read(5,*) l(i),r(i)
enddo

do i=1,h
    do j=1,w
        locationy(a(i,j))=i
        locationx(a(i,j))=j
enddo
enddo

do i=1,d
    j=1
    do while (i+j*d<=h*w)    
        mpp(i+j*d)=mpp(i+j*d-d)+abs(locationx(i+j*d-d)-locationx(i+j*d))+abs(locationy(i+j*d-d)-locationy(i+j*d))
!        write(6,*) i,i+j*d, abs(locationx(i)-locationx(i+j*d)),abs(locationy(i)-locationy(i+j*d))
        j=j+1


enddo
enddo

!do i=1,h*w
!    write(6,*) locationx(i), locationy(i)
!enddo

do i=1,q
    mp=0
    distance=0

    write(6,"(i0)") mpp(r(i))-mpp(l(i))
enddo

!write(6,"(i0)") (mpp(i),i=1,h*w)

stop
end