# なぜ自分のコードはこんなに長いのか(´・ω・`) N, K = gets.split.map(&:to_i) S = gets.chomp def calc(want, kuji) raise unless want > 0 buy = 0 for i in 0...N do if kuji > 0 then kuji -= 1 else buy += 1 end kuji += S[i].to_i want -= 1 break if want <= 0 end return buy, kuji end buy_sum = 0 want = K buy_prev = nil kuji_prev = 0 while want > 0 do buy, kuji = calc(want, kuji_prev) break if buy <= 0 && kuji >= kuji_prev #クジだけでやっていける if buy == buy_prev && kuji == kuji_prev then #パターンに入った q, r = want.divmod(N) buy_sum += buy * q want = r if want > 0 then buy, kuji = calc(want, kuji_prev) buy_sum += buy want -= N end else buy_sum += buy want -= N end buy_prev = buy kuji_prev = kuji end puts buy_sum