import std.stdio, std.string, std.range, std.conv, std.array, std.algorithm, std.math, std.typecons;

void main() {
    long H, W, D;
    readf("%d %d %d\n", &H, &W, &D);

    long[] x = new long[H*W];
    long[] y = new long[H*W];

    foreach (j; 0..H) {
        auto A = readln.split.to!(long[]);
        foreach (i; 0..W) {
            x[A[i]-1] = i;
            y[A[i]-1] = j;
        }
    }
    auto Q = readln.chomp.to!long;
    auto Ls = new long[Q];
    auto Rs = new long[Q];
    foreach (i; 0..Q) {
        long L, R;
        readf("%d %d\n", &L, &R);
        Ls[i] = L-1;
        Rs[i] = R-1;
    }
    long[] cost = new long[H*W];
    foreach (i; D..H*W) {
        cost[i] = abs(x[i] - x[i-D]) + abs(y[i] - y[i-D]);
    }
    foreach (i; 0..cost.length-D) {
        cost[i+D] += cost[i];
    }

    foreach (i; 0..Q) {
        auto L = Ls[i];
        auto R = Rs[i];

        writeln(cost[R] - cost[L]);
    }
}

