#include <bits/stdc++.h>
using namespace std;
typedef vector<int> VI;
typedef pair <int,int> ii;
typedef long long LL;
#define pb push_back
const int INF = 2147483647;
const int N = 100005;
int z, n, l, r, act, i, res;
VI v, v2;
char t[N];
bool cmp(int a, int b) {
return a > b;
}
int go() {
int res = 0;
for (int i=0;i<v2.size();i++) if (v2[i] - 1 - 4 * i >= 0) res += max(1, v2[i] - 1 - 4 * i);
//printf("%d\n", res);
return res;
}
int main() {
scanf("%d", &z);
while (z--) {
scanf("%d", &n);
scanf("%s", t);
v.clear();
l = r = 0;
for (l=0;l<n && t[l] == '0';l++) {}
for (r=n-1;r>=0 && t[r] == '0';r--) {}
if (l == n) {
printf("0\n");
continue;
}
act = 0;
for (i=l;i<=r;i++) {
if (t[i] == '1' && act > 0) {
v.pb(act);
act = 0;
} else if (t[i] == '0') act++;
}
r = n - r - 1;
sort(v.begin(), v.end(), cmp);
v2.clear();
for (auto& w : v) v2.pb(w);
res = go();
if (max(l, r) >= 1) {
v2.clear();
for (auto& w : v) if (w > 2) v2.pb(w - 2);
res = max(res, go() + max(l, r));
}
if (min(l, r) >= 1) {
v2.clear();
for (auto& w : v) if (w > 4) v2.pb(w - 4);
res = max(res, go() + l + r - 1);
}
printf("%d\n", n - res);
}
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 | #include <bits/stdc++.h> using namespace std; typedef vector<int> VI; typedef pair <int,int> ii; typedef long long LL; #define pb push_back const int INF = 2147483647; const int N = 100005; int z, n, l, r, act, i, res; VI v, v2; char t[N]; bool cmp(int a, int b) { return a > b; } int go() { int res = 0; for (int i=0;i<v2.size();i++) if (v2[i] - 1 - 4 * i >= 0) res += max(1, v2[i] - 1 - 4 * i); //printf("%d\n", res); return res; } int main() { scanf("%d", &z); while (z--) { scanf("%d", &n); scanf("%s", t); v.clear(); l = r = 0; for (l=0;l<n && t[l] == '0';l++) {} for (r=n-1;r>=0 && t[r] == '0';r--) {} if (l == n) { printf("0\n"); continue; } act = 0; for (i=l;i<=r;i++) { if (t[i] == '1' && act > 0) { v.pb(act); act = 0; } else if (t[i] == '0') act++; } r = n - r - 1; sort(v.begin(), v.end(), cmp); v2.clear(); for (auto& w : v) v2.pb(w); res = go(); if (max(l, r) >= 1) { v2.clear(); for (auto& w : v) if (w > 2) v2.pb(w - 2); res = max(res, go() + max(l, r)); } if (min(l, r) >= 1) { v2.clear(); for (auto& w : v) if (w > 4) v2.pb(w - 4); res = max(res, go() + l + r - 1); } printf("%d\n", n - res); } return 0; } |
English