fun main(args : Array<String>) {
        val (h, w, d) = readLine()!!.split(" ").map { it.toInt() }
        val size = h * w
        val array = Array(size) { Pair(0, 0) }.apply {
            (0 until h).forEach { y -> readLine()!!.split(" ").forEachIndexed { x, a -> set(a.toInt() - 1, Pair(x, y)) } }
        }
        val sum = Array(size) { 0 }.apply {
            (0 until size).forEach { i ->
                if (i < d) set(i, 0)
                else set(i, get(i - d) + Math.abs(array[i].first - array[i - d].first) + Math.abs(array[i].second - array[i - d].second))
            }
        }
        (1..readLine()!!.toInt()).forEach {
            readLine()!!.split(" ").let { println(sum[it[1].toInt() - 1] - sum[it[0].toInt() - 1]) }
        }
}