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

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

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,h*w
!    write(6,*) locationx(i), locationy(i)
!enddo

do i=1,q
    mp=0
    distance=0
    do while (l(i)<r(i))    
        mp=mp+abs(locationx(l(i))-locationx(l(i)+d))+abs(locationy(l(i))-locationy(l(i)+d))
        l(i)=l(i)+d

    enddo
    write(6,"(i0)") mp
enddo


stop
end