from functools import lru_cache def solve(N, S): if list(S) == sorted(S): return 0 S2 = S * 2 # get #0 in S[l:r] by zero_cnt[r] - zero_cnt[l] zero_cnt = [0] one_cnt = [0] for c in S2: zero_cnt.append(zero_cnt[-1] + int(c == '0')) one_cnt.append(one_cnt[-1] + int(c == '1')) @lru_cache(10) def calc(l, t, r): left0 = zero_cnt[t + 1] - zero_cnt[l] right1 = one_cnt[r + 1] - one_cnt[t + 1] end = t + right1 rem = (N - 1 - end) % N assert l <= t <= end <= r if end < N: loop = max(left0, right1) elif t < N: rskip = int(bool(one_cnt[N + 1] - one_cnt[t + 1])) loop = max(left0 - 1, right1 - rskip) else: lskip = int(bool(zero_cnt[N + 1] - zero_cnt[l + 1])) loop = max(left0 - lskip, right1) loop = max(0, loop) return loop * N + rem ones = [] for i, c in enumerate(S2): if c == '1': ones.append(i) answer = 10 ** 18 # debug = [] t = -1 for i in range(one_cnt[N]): l = ones[i] r = ones[i + one_cnt[N] - 1] # debug.append([-1] * l + [calc(l, t, r) for t in range(l, r + 1)]) t = max(l, t) while True: c = calc(l, t, r) # print(l, t, r, c) nt = t + 1 while nt <= r and c == calc(l, nt, r): nt += 1 if nt == r + 1 or c < calc(l, nt, r): break t = nt answer = min(answer, c) # print(*debug, sep='\n') return answer def slow(N, S): parent = dict() sorted_S = sorted(S) q = [(0, list(S))] while True: nq = [] for t, Sp in q: # print(Sp, sorted_S) if Sp == sorted_S: tr = [] Sp_str = ''.join(Sp) while Sp_str != S: tr.append(Sp_str) Sp_str = parent[Sp_str] tr.append(S) print(tr[::-1]) for i in range(len(tr)): k = i % N print(tr[-i-1][k:] + tr[-i-1][:k]) return t newSp = [Sp[-1]] + Sp[:-1] nq.append((t + 1, newSp)) if ''.join(newSp) not in parent: parent[''.join(newSp)] = ''.join(Sp) newSp = [Sp[0]] + [Sp[-1]] + Sp[1:-1] nq.append((t + 1, newSp)) if ''.join(newSp) not in parent: parent[''.join(newSp)] = ''.join(Sp) q = nq def main(): N = int(input()) S = input() print(solve(N, S)) # print(slow(N, S)) def test(t): import random for i in range(t): r = random.randint(1, 2 ** 9) S = bin(r)[2:] N = len(S) print(N, S) ac = slow(N, S) wa = solve(N, S) print(ac, wa) assert ac == wa main() # test(1000)