#include <cstdio> #include <vector> #include <algorithm> using namespace std; #define FOR(i,a,b) for(int (i)=(int)(a); (i)!=(int)(b); ++(i)) int t, n; char S[100005]; int solve() { int occupied = 0; FOR(i,0,n) if (S[i] == '1') ++occupied; if (occupied == 0) return 0; if (occupied == n) return n; vector<int> P1; int L = 0, R = 0; while (S[L] != '1') ++L; while (S[n-1-R] != '1') ++R; if (L>0) P1.push_back(L); if (R>0) P1.push_back(R); if (P1.size() == 2 && P1[0] < P1[1]) swap(P1[0], P1[1]); vector<int> P2; int len = 0; FOR(i,0,n-L-R) { if (S[L+i] == '1') { if (len > 0) P2.push_back(len); len = 0; } else ++len; } sort(P2.begin(), P2.end()); reverse(P2.begin(), P2.end()); if (P2.size() == 0) { if (P1.size() == 1) return occupied; return occupied + 1; } int result = 0; int res_2 = 0; FOR(i,0,P2.size()+1){ int res_1 = 0; if (P1.size() >= 1) res_1 += max(0, P1[0] - 2*i); if (P1.size() == 2) res_1 += max(0, P1[1] - 2*i - 1); if (i>0) { int val = max(0, P2[i-1] - 1 - 4*(i-1)); res_2 += val; } result = max(result, res_1 + res_2); } return n - result; } int main() { scanf("%d", &t); while (t--) { scanf("%d", &n); scanf("%s", &S); printf("%d\n", 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 | #include <cstdio> #include <vector> #include <algorithm> using namespace std; #define FOR(i,a,b) for(int (i)=(int)(a); (i)!=(int)(b); ++(i)) int t, n; char S[100005]; int solve() { int occupied = 0; FOR(i,0,n) if (S[i] == '1') ++occupied; if (occupied == 0) return 0; if (occupied == n) return n; vector<int> P1; int L = 0, R = 0; while (S[L] != '1') ++L; while (S[n-1-R] != '1') ++R; if (L>0) P1.push_back(L); if (R>0) P1.push_back(R); if (P1.size() == 2 && P1[0] < P1[1]) swap(P1[0], P1[1]); vector<int> P2; int len = 0; FOR(i,0,n-L-R) { if (S[L+i] == '1') { if (len > 0) P2.push_back(len); len = 0; } else ++len; } sort(P2.begin(), P2.end()); reverse(P2.begin(), P2.end()); if (P2.size() == 0) { if (P1.size() == 1) return occupied; return occupied + 1; } int result = 0; int res_2 = 0; FOR(i,0,P2.size()+1){ int res_1 = 0; if (P1.size() >= 1) res_1 += max(0, P1[0] - 2*i); if (P1.size() == 2) res_1 += max(0, P1[1] - 2*i - 1); if (i>0) { int val = max(0, P2[i-1] - 1 - 4*(i-1)); res_2 += val; } result = max(result, res_1 + res_2); } return n - result; } int main() { scanf("%d", &t); while (t--) { scanf("%d", &n); scanf("%s", &S); printf("%d\n", solve()); } } |