#include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
string s;
cin >> s;
int x = 0;
vector < int > a;
for (int i = 0; i < n; i++) {
if (s[i] == '1') {
a.push_back(x);
x = 0;
} else x++;
}
if (x == n) {
cout << "0\n";
return;
}
a.push_back(x);
int l = a[0], r = a.back();
a.erase(a.begin());
a.pop_back();
bool used_l = false, used_r = false;
sort(a.rbegin(), a.rend());
int d = 0, ans = 0;
for (int i = 0; i < (int)a.size(); i++) {
if (a[i] <= d) break;
int val = a[i] - 2 * d - 1;
if (val <= 0) break;
if (used_l && used_r) {
ans += val;
d += 2;
} else if (!used_l && !used_r) {
int mx = max(l - d, r - d);
if (val >= mx) {
ans += val;
d += 2;
} else if (l - d == mx) {
ans += l - d;
used_l = true;
d++;
} else {
ans += r - d;
used_r = true;
d++;
}
} else if (used_l) {
if (val >= l - d) {
ans += val;
d += 2;
} else {
ans += l - d;
used_l = true;
d++;
}
} else if(used_r) {
if (val >= r - d) {
ans += val;
d += 2;
} else {
ans += r - d;
used_r = true;
d++;
}
}
}
if (!used_l) {
ans += max(0, l - d);
d++;
}
if (!used_r) ans += max(0, r - d);
cout << n - ans << "\n";
}
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int z;
cin >> z;
while (z--) solve();
}
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | #include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; string s; cin >> s; int x = 0; vector < int > a; for (int i = 0; i < n; i++) { if (s[i] == '1') { a.push_back(x); x = 0; } else x++; } if (x == n) { cout << "0\n"; return; } a.push_back(x); int l = a[0], r = a.back(); a.erase(a.begin()); a.pop_back(); bool used_l = false, used_r = false; sort(a.rbegin(), a.rend()); int d = 0, ans = 0; for (int i = 0; i < (int)a.size(); i++) { if (a[i] <= d) break; int val = a[i] - 2 * d - 1; if (val <= 0) break; if (used_l && used_r) { ans += val; d += 2; } else if (!used_l && !used_r) { int mx = max(l - d, r - d); if (val >= mx) { ans += val; d += 2; } else if (l - d == mx) { ans += l - d; used_l = true; d++; } else { ans += r - d; used_r = true; d++; } } else if (used_l) { if (val >= l - d) { ans += val; d += 2; } else { ans += l - d; used_l = true; d++; } } else if(used_r) { if (val >= r - d) { ans += val; d += 2; } else { ans += r - d; used_r = true; d++; } } } if (!used_l) { ans += max(0, l - d); d++; } if (!used_r) ans += max(0, r - d); cout << n - ans << "\n"; } int main() { ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); int z; cin >> z; while (z--) solve(); } |
English