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

alias A = Tuple!(int, "i", int, "j");

int H, W, D, Q;
A[300*300+1] AS;
long[int][300*300+1] DS;

void main()
{
    auto hwd = readln.split.to!(int[]);
    H = hwd[0];
    W = hwd[1];
    D = hwd[2];

    foreach (j; 0..H)
        foreach (i, e; readln.split.to!(int[]))
            AS[e] = A(i.to!int, j);
    
    foreach (x; 1..H*W+1) {
        DS[x][x] = 0;
        auto x_ = x;
        long d;
        while (x_ <= H*W) {
            auto a = AS[x_];
            x_ += D;
            auto ad = AS[x_];
            d += abs(a.i - ad.i) + abs(a.j - ad.j);
            DS[x][x_] = d;
        }
    }

    Q = readln.chomp.to!int;
    foreach (_; 0..Q) {
        auto lr = readln.split.to!(int[]);
        auto L = lr[0];
        auto R = lr[1];
        writeln(DS[L][R]);
    }
}