#include using namespace std; unsigned long long solve(int N, string S) { if (vector(S.begin(), S.end()) == vector(S.begin(), S.end())) { return 0; } string S2 = S + S; // 计算 S[l:r] 中 '0' 的数量,zero_cnt[r] - zero_cnt[l] vector zero_cnt(S2.length() + 1, 0); vector one_cnt(S2.length() + 1, 0); for (char c : S2) { zero_cnt.push_back(zero_cnt.back() + (c == '0')); one_cnt.push_back(one_cnt.back() + (c == '1')); } unordered_map cache; function calc = [&](int l, int t, int r) -> int { int left0 = zero_cnt[t + 1] - zero_cnt[l]; int right1 = one_cnt[r + 1] - one_cnt[t + 1]; int end = t + right1; int rem = (N - 1 - end) % N; assert(l <= t && t <= end && end <= r); if (end < N) { if (right1) { int rskip = (one_cnt[N + 1] - one_cnt[t + 1]) ? 1 : 0; right1 = right1 + 1 - rskip; } return max(left0, right1) * N + rem; } else if (t < N) { int rskip = (one_cnt[N + 1] - one_cnt[t + 1]) ? 1 : 0; return max(left0 - 1, right1 - rskip) * N + rem; } else { int lskip = (zero_cnt[N + 1] - zero_cnt[l + 1]) ? 1 : 0; return max(left0 - lskip, right1) * N + rem; } }; vector ones; for (int i = 0; i < S2.length(); i++) { if (S2[i] == '1') { ones.push_back(i); } } unsigned long long answer = 1e18; int t = -1; for (int i = 0; i < one_cnt[N]; i++) { int l = ones[i]; int r = ones[i + one_cnt[N] - 1]; t = max(l, t); int c = calc(l, t, r); while (true) { int nt = t + 1; while (nt <= r && c == calc(l, nt, r)) { nt++; } if (nt == r + 1 || c < calc(l, nt, r)) { break; } t = nt; } answer = min(answer, (unsigned long long)c); } return answer; } int main() { int N; cin >> N; string S; cin >> S; cout << solve(N, S) << endl; return 0; }