n = gets.to_i a = gets.split.map &:to_i b = Array.new(40) { [0] * n } b.each_index do |i| b[i] = (i == 0 ? a : b[i - 1].map_with_index { |v, j| v + b[i - 1][(v + j) % n] }) end gets.to_i.times do k = gets.to_i puts b.each_with_index.reduce(0) { |acc, (v, i)| acc + (k[i] == 1 ? v[acc % n] : 0) } end