fun main(args: Array<String>) {
    val sc = java.util.Scanner(System.`in`)
    val h = sc.nextInt()
    val w = sc.nextInt()
    val d = sc.nextInt()

    data class Pos(val x: Int, val y: Int, var dsum: Int = 0)

    val A: Array<Array<Pos>> = Array(d) { Array(h * w / d + 1) { Pos(9999, 9999) } }

    for (y in 0 until h) {
        for (x in 0 until w) {
            val v = sc.nextInt() - 1 // to 0 origin
            A[v % d][v / d] = Pos(x, y)
        }
    }
    for (di in 0 until d) {
        var dsum = 0
        if (A[di].isNotEmpty()) {
            var t = A[di][0]
            for (i in 1 until A[di].count()) {
                val tnext = A[di][i]
                dsum += Math.abs(t.x - tnext.x) + Math.abs(t.y - tnext.y)
                tnext.dsum = dsum
                t = tnext
            }
        }
    }

    val q = sc.nextInt()
    for (i in 0 until q) {
        var m = 0
        val L = sc.nextInt() - 1
        val R = sc.nextInt() - 1

        val Ld = A[L % d][L / d].dsum
        val Rd = A[R % d][R / d].dsum

        println(Rd - Ld)
    }
}
