#include <iostream>
#include <algorithm>
using namespace std;
int main(void){
  int h,w,d,q,i,j,a,p[90010][2],c[90010]={};
  cin >> h >> w >> d;
  for (i=0;i<h;i++) for (j=0;j<w;j++){
    cin >> a;
    p[a][0]=i;
    p[a][1]=j;
  }
  for (i=d+1;i<=h*w;i++) c[i]+=c[i-d]+abs(p[i][0]-p[i-d][0])+abs(p[i][1]-p[i-d][1]);
  
  cin >> q;
  for (i=0;i<q;i++){
    int l,r;
    cin >> l >> r;
    cout << c[r]-c[l] << endl;
  }
  return 0;
}