import java.util.Comparator

fun main(args: Array<String>) {
    val (H, W, D) = readLine()!!.split(" ").map{it.toInt()}
    val A = Array(H) {
        readLine()!!.split(" ").map{it.toInt()}
    }

    val B = Array(H * W) {
        val i = it / W
        val j = it % W
        Triple(A[i][j], i, j)
    }.sortedWith(Comparator { a, b -> a.first.compareTo(b.first)})

    val C = Array(H * W) {
        if (it < D) {
            0
        } else {
            val s = B[it - D]
            val t = B[it]
            Math.abs(s.second - t.second) + Math.abs(s.third - t.third)
        }
    }

    for (i in D until C.size) {
        C[i] += C[i - D]
    }

    val Q = readLine()!!.toInt()
    for (i in 1..Q) {
        val (L, R) = readLine()!!.split(" ").map{it.toInt()}

        println(C[R - 1] - C[L - 1])
    }
}
