#include <bits/stdc++.h> using namespace std; #define pb push_back int calc(const vector<int>& v, int t) { int ans = 0; for (int x : v) { int left = x - 2 * t; if (left <= 0) continue; if (left == 1) { ans += 1; t += 1; } else { ans += left - 1; t += 2; } } return ans; } int solve() { int n; string s; cin >> n >> s; size_t b = s.find('1'); if (b == s.npos) return 0; int e = s.rfind('1'); vector<int> v; int c = 0; for (int i = b + 1; i <= e; ++i) if (s[i] == '0') ++c; else if (c) { v.pb(c); c = 0; } sort(v.begin(), v.end(), greater<int>()); int l = b, r = n - 1 - e; if (l < r) swap(l, r); return n - max({ calc(v, 0), calc(v, 1) + l, calc(v, 2) + l + r - 1}); } int main() { ios_base::sync_with_stdio(false); int t; cin >> t; while (t--) cout << solve() << '\n'; return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | #include <bits/stdc++.h> using namespace std; #define pb push_back int calc(const vector<int>& v, int t) { int ans = 0; for (int x : v) { int left = x - 2 * t; if (left <= 0) continue; if (left == 1) { ans += 1; t += 1; } else { ans += left - 1; t += 2; } } return ans; } int solve() { int n; string s; cin >> n >> s; size_t b = s.find('1'); if (b == s.npos) return 0; int e = s.rfind('1'); vector<int> v; int c = 0; for (int i = b + 1; i <= e; ++i) if (s[i] == '0') ++c; else if (c) { v.pb(c); c = 0; } sort(v.begin(), v.end(), greater<int>()); int l = b, r = n - 1 - e; if (l < r) swap(l, r); return n - max({ calc(v, 0), calc(v, 1) + l, calc(v, 2) + l + r - 1}); } int main() { ios_base::sync_with_stdio(false); int t; cin >> t; while (t--) cout << solve() << '\n'; return 0; } |