#include <iostream> #include <vector> #include <algorithm> #include <utility> void solve() { long n; std::string b; std::cin >> n >> b; long size = 0; bool first = true; std::vector<long> R; long r1 = 0, r2 = 0; for (char c : b) { if (c == '0') ++size; else if (c == '1') { if (first) r1 = size; else R.push_back(size); first = false; size = 0; } } r2 = size; std::sort(R.begin(), R.end(), std::greater<long>()); long max_saved = 0; for (int i=0;i<=3;++i) { long saved = 0; long level = 0; if (i&1) { saved += std::max(r1 - level/2, 0l); level += 2; } if (i&2) { saved += std::max(r2 - level/2, 0l); level += 2; } for (long r : R) { if (r-level == 1 || r-level == 2) { saved += 1; level += 2; } else if (level+1 < r) { saved += r - level - 1; level += 4; } } max_saved = std::max(saved, max_saved); } std::cout << n-max_saved << "\n"; } int main() { std::ios_base::sync_with_stdio(0); long t; std::cin >> t; while (t--) solve(); 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 | #include <iostream> #include <vector> #include <algorithm> #include <utility> void solve() { long n; std::string b; std::cin >> n >> b; long size = 0; bool first = true; std::vector<long> R; long r1 = 0, r2 = 0; for (char c : b) { if (c == '0') ++size; else if (c == '1') { if (first) r1 = size; else R.push_back(size); first = false; size = 0; } } r2 = size; std::sort(R.begin(), R.end(), std::greater<long>()); long max_saved = 0; for (int i=0;i<=3;++i) { long saved = 0; long level = 0; if (i&1) { saved += std::max(r1 - level/2, 0l); level += 2; } if (i&2) { saved += std::max(r2 - level/2, 0l); level += 2; } for (long r : R) { if (r-level == 1 || r-level == 2) { saved += 1; level += 2; } else if (level+1 < r) { saved += r - level - 1; level += 4; } } max_saved = std::max(saved, max_saved); } std::cout << n-max_saved << "\n"; } int main() { std::ios_base::sync_with_stdio(0); long t; std::cin >> t; while (t--) solve(); return 0; } |