Kr, Kb = gets.split.take(2).map(&:to_i) S = gets.chomp def ng_at(s, i) r = [] range = 0...s.size !case s[i] when ?R r << i - Kr if range.cover?(i - Kr) && s[i - Kr] == ?R r << i + Kr if range.cover?(i + Kr) && s[i + Kr] == ?R when ?B r << i - Kb if range.cover?(i - Kb) && s[i - Kb] == ?B r << i + Kb if range.cover?(i + Kb) && s[i + Kb] == ?B else end r end def valid?(s) !s.size.times.any?{|i| !ng_at(s, i).empty? } end def count_ng(s) count = 0 s.size.times{|i| count += ng_at(s, i).size } count end q = {S=>1} while !q.empty? qq = {} q.keys.each{|s| s.size.times{|i| ngs = ng_at(s, i) ngs.each{|ng_idx| t = s[0...ng_idx] + s[ng_idx+1..-1] if valid?(t) p t.size exit end qq[t] = 1 } } } q = qq end