local io_read = io.read
local math_abs = math.abs
local H, W, D = io_read("*n", "*n", "*n")
local AH = {}
local AW = {}
for h=1,H do
  for w=1,W do
    local a = io_read("*n")
    AH[a] = h
    AW[a] = w
  end
end
local CC = {}
for i=1,H*W-D do
  CC[i] = math_abs(AH[i] - AH[i+D]) + math_abs(AW[i] - AW[i+D])
end

local Q = io_read("*n")
local C = {}
for q=1,Q do
  local l, r = io_read("*n", "*n")
  local cost = 0
  for x=l,r-D,D do
    cost = cost + CC[x]
  end
  C[q] = cost
end
print(table.concat(C, "\n"))
