#include <bits/stdc++.h>
using namespace std;
int main(){
	int H, W, D, Q; 
	cin >> H >> W >> D; 
	int A[90010][3] = {};
	for(int i = 0; i < H; i++){
		for(int j = 0; j < W; j++){
			int B; 
			cin >> B; 
			A[B][0] = i, A[B][1] = j; 
		}
    }
	int B[90010] = {}; 
	for(int i = D + 1; i <= H * W; i++){
		B[i] = B[i - D] + abs(A[i][0] - A[i-D][0]) + abs(A[i][1] - A[i-D][1]); 
	}
    cin >> Q; 
	for(int j = 0; j < Q; j++){
	int L, R; 
	cin >> L >> R; 
	cout << B[R] - B[L] << endl; 
	}
}