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 CCC = {}
for i=1,D do
  CCC[i] = 0
end
for i=1,H*W-D do
  CCC[i+D] = CCC[i] + CC[i]
end

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