fun main(args: Array<String>) {
    val (H, W, D) = readLine()!!.split(" ").map { it.toInt() }
    val A = mutableListOf<IntArray>()
    (1..H).forEach {
        val ai = readLine()!!.split(" ").map { it.toInt() }.toIntArray()
        A.add(ai)
    }
    // O(HW) Create function to retrieve the poistion of num N in O(1)
    val numToPosition = Array(H * W + 1, { Pair(-1, -1) })
    (0 until H).forEach {h ->
        (0 until W).forEach {w ->
            val num = A[h][w]
            numToPosition[num] = Pair(h, w)
        }
    }
    fun getPositionByNumber(num: Int) : Pair<Int, Int> {
        return numToPosition[num]
    }

    val Q = readLine()!!.toInt()

    // Return cost
    fun useMagic(i: Int, j: Int, x: Int, y: Int) : Int {
        return Math.abs(x - i) + Math.abs(y - j)
    }

    val a = IntArray(H * W + 1)
    a.fill(0)

    // O(HW)
    (1..D).forEach {d ->
        var r = d
        a[r] = 0
        while (r + D <= H * W) {
            val (i, j) = getPositionByNumber(r)
            val (x, y) = getPositionByNumber(r + D)
            a[r + D] = a[r] + useMagic(i, j, x, y)
            r += D
        }
    }

    // O(Q)
    (1..Q).forEach {
        val (L, R) = readLine()!!.split(" ").map { it.toInt() }
        println(a[R] - a[L])
    }
}
