#include <bits/stdc++.h> using namespace std; constexpr int LIM = 1e5; int values[LIM + 3]; int fl[2]; void setCnt(int& k, int& l, int& m, int& best, int bc, int sv) { int tv, vc = sv, mc = 0, lc = 0, kc = 0; for(int i = 0; i <= bc; ++i) { tv = max(0, values[i] - 2 * vc); if(tv == 0) break; if(tv == 2 || tv == 1) { ++mc; ++vc; best += 1; } else if(tv == 3) { ++lc; vc += 2; best += 2; } else { ++kc; vc += 2; best += tv - 1; } } k = kc; l = lc + kc; m = l + mc; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t, n; cin >> t; string input; while(t--) { cin >> n >> input; int ci = 0, bc = -1; fl[0] = fl[1] = 0; if(input[0] == '0') { while(ci < n && input[ci++] == '0') { ++fl[0]; } } while(ci < n) { if(input[ci] == '0' && input[ci - 1] == '1') { values[++bc] = 1; } else if (input[ci] == '0') { ++values[bc]; } ++ci; } if(input[n - 1] == '0') { fl[1] = values[bc]; --bc; } if(fl[1] > fl[0]) swap(fl[1], fl[0]); if(bc >= 0) sort(values, values + bc + 1, greater<int>()); int m, k, l, best = 0, res; setCnt(k, l, m, best, bc, 0); res = best; if(fl[0] >= m + k) { res = best + fl[0] - m - k; best = 0; setCnt(k, l, m, best, bc, 1); if(fl[1] - 1 > m + k) { res = best + fl[0] + fl[1] - 1 - m - k; } } cout << n - res << "\n"; } }
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 | #include <bits/stdc++.h> using namespace std; constexpr int LIM = 1e5; int values[LIM + 3]; int fl[2]; void setCnt(int& k, int& l, int& m, int& best, int bc, int sv) { int tv, vc = sv, mc = 0, lc = 0, kc = 0; for(int i = 0; i <= bc; ++i) { tv = max(0, values[i] - 2 * vc); if(tv == 0) break; if(tv == 2 || tv == 1) { ++mc; ++vc; best += 1; } else if(tv == 3) { ++lc; vc += 2; best += 2; } else { ++kc; vc += 2; best += tv - 1; } } k = kc; l = lc + kc; m = l + mc; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t, n; cin >> t; string input; while(t--) { cin >> n >> input; int ci = 0, bc = -1; fl[0] = fl[1] = 0; if(input[0] == '0') { while(ci < n && input[ci++] == '0') { ++fl[0]; } } while(ci < n) { if(input[ci] == '0' && input[ci - 1] == '1') { values[++bc] = 1; } else if (input[ci] == '0') { ++values[bc]; } ++ci; } if(input[n - 1] == '0') { fl[1] = values[bc]; --bc; } if(fl[1] > fl[0]) swap(fl[1], fl[0]); if(bc >= 0) sort(values, values + bc + 1, greater<int>()); int m, k, l, best = 0, res; setCnt(k, l, m, best, bc, 0); res = best; if(fl[0] >= m + k) { res = best + fl[0] - m - k; best = 0; setCnt(k, l, m, best, bc, 1); if(fl[1] - 1 > m + k) { res = best + fl[0] + fl[1] - 1 - m - k; } } cout << n - res << "\n"; } } |