# frozen_string_literal: true in_x, in_y, in_n = gets.chomp.split.map(&:to_i) in_uv = in_n.times.map { gets.chomp.split.map(&:to_i) } in_uv.each do |u, v| if (u - 1) / in_y == (v - 1) / in_y puts (u - v).abs else u_distance = if u == 0 0 else (u - 1) % in_y + 1 end v_distance = if v == 0 0 else (v - 1) % in_y + 1 end puts u_distance + v_distance end end