fun main(args: Array<String>) {
    val (h,w,d)= readLine()!!.split(" ").map { it.toInt() }
    val a= (1..h).map { readLine()!!.split(" ").map { it.toInt() }}
    val q= readLine()!!.toInt()
    val lr =(1..q).map { readLine()!!.split(" ").map { it.toInt() } }

    val p=Array(d){ IntArray(1+h*w/d) }
    for(i in 0..h-1){
        for(j in 0..w-1){
            val m = a[i][j]
            p[m%d][m/d]=i*w+j
        }
    }

    val mp = Array(d){  IntArray(1+h*w/d)}
    for(i in 0..d-1){
        for(j in 1..mp[i].lastIndex){
            val dx = Math.abs( p[i][j-1]%w - p[i][j]%w )
            val dy = Math.abs( p[i][j-1]/w - p[i][j]/w )
            mp[i][j] = mp[i][j-1] + (dx+dy) //jの累積和
        }
    }

    lr.fold(StringBuilder()) { sb,it->
        val l=it[0]
        val r=it[1]
        sb.append( mp[r%d][r/d]-mp[l%d][l/d] ).append("\n")
    }.let { print(it) }


}