Kr, Kb = gets.split.take(2).map(&:to_i) S = gets.chomp def valid?(s) !s.size.times.any?{|i| case s[i] when ?R i - Kr >= 0 && s[i - Kr] == ?R when ?B i - Kb >= 0 && s[i - Kb] == ?B end } end $memo = {} $ans = 12 def f(s) n = s.size $memo[s] ||= if valid?(s) || n <= $ans $ans = [$ans, n].max else n.times.map{|i| next 0 if s[i] == ?W t = s[0...i] + s[i + 1..-1] f(t) }.max end end p f(S)