input = $<.read.split N, X, Y = input.shift(3).map(&:to_i) group_by_ai = Array.new(2) { [0] * (X + Y) } N.times do |i| p = input.shift.to_i c = input.shift case c when ?A group_by_ai[0][i % (X + Y)] += p when ?B group_by_ai[1][i % (X + Y)] += p end end sum = (0 ... X + Y).sum { |i| group_by_ai[0][i] } a = (0 ... X + Y).map { |i| group_by_ai[1][i] - group_by_ai[0][i] } a.sort! a.reverse! sum += a[0, Y].sum puts sum