import std.conv, std.stdio, std.string, std.typecons, std.math;

alias Tuple!(int,int) p;

void main() {
	int [] hwd = readln().chomp().split().to!(int[]);
	int H = hwd[0], W = hwd[1];
	int D = hwd[2];
	int [][] A;
	p [] crd;
	A.length = H;
	crd.length = H*W+1;
	foreach(i; 0..H) {
		A[i] = readln().chomp().split().to!(int[]);
		foreach(j; 0..W) {
			crd[A[i][j]] = p(i,j);
		}
	}

	int [][] cost;
	cost.length = 20;
	cost[0].length = H*W+1;
	foreach(i; 1..H*W+1) {
		if(i+D <= H*W) {
			cost[0][i] = to!(int)(abs(crd[i][0] - crd[i+D][0]) + abs(crd[i][1] - crd[i+D][1]));
		}
		else {
			cost[0][i] = -1;
		}
	}
	foreach(i; 1..20) {
		cost[i].length = H*W+1;
		foreach(j; 1..H*W+1) {
			if(j+D*to!(long)(1<<i) <= H*W) {
				cost[i][j] = cost[i-1][j] + cost[i-1][j+D*(1<<(i-1))];
			}
			else {
				cost[i][j] = -1;
			}
		}
	}
	int Q = readln().chomp().to!(int);
	foreach(i; 0..Q) {
		int [] lr = readln().chomp().split().to!(int[]);
		int it = (lr[1] - lr[0]) / D;
		int j = 0, k = lr[0];
		long res = 0;
		while(it) {
			if(it & 1) {
				res += cost[j][k];
				k += D*(1 << j);
			}
			j++;
			it /= 2;
		}

		writeln(res);
	}
}
