def get_ints gets.split.map(&:to_i) end n, q = get_ints a = get_ints s = gets.chomp t = get_ints cost = Array.new(2) { [0] * 30 } (0 ... 2).each do |i| (0 ... 30).each do |j| x = i (0 ... n).each do |k| if s[k] == '0' y = x & (a[k] >> j & 1) else y = x | (a[k] >> j & 1) end cost[i][j] += (y - x).abs << j x = y end end end (0 ... q).each do |i| answer = (0 ... 30).map { |j| cost[t[i] >> j & 1][j] }.sum puts answer end