#include <iostream> #include <vector> #include <algorithm> using namespace std; void solve(int tc) { int c; string i; vector<int> b; int s = 0; int e = 0; cin >> c >> i; for (int p = 0; p < c; ++p) { while (p < c && i[p] == '1') { ++p; } int z = 0; while (p < c && i[p] == '0') { ++p; ++z; } if(z > 0){ if(z == p){ s = z; } else if (p == c){ e = z; } else { b.push_back(z); } } } sort(b.begin(), b.end()); int t = 0; int r = 0; while(true){ int st = s - t; int et = e - t; int bl = b.size() > 0 ? b.back() - 2 * t : 0; int sd = st; int ed = et; int bd = (bl + 1 ) / 2; if(sd <= 0 && ed <= 0 && bd <= 0){ break; } if(sd >= ed && sd >= bd){ r += st; s = 0; ++t; } else if (ed >= bd) { r += et; e = 0; ++t; } else { r += bl > 1 ? (bl - 1) : 1; b.pop_back(); t += 2; } } cout << c - r << endl; } int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; for (int i = 0; i < tc; ++i) { solve(i); } 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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | #include <iostream> #include <vector> #include <algorithm> using namespace std; void solve(int tc) { int c; string i; vector<int> b; int s = 0; int e = 0; cin >> c >> i; for (int p = 0; p < c; ++p) { while (p < c && i[p] == '1') { ++p; } int z = 0; while (p < c && i[p] == '0') { ++p; ++z; } if(z > 0){ if(z == p){ s = z; } else if (p == c){ e = z; } else { b.push_back(z); } } } sort(b.begin(), b.end()); int t = 0; int r = 0; while(true){ int st = s - t; int et = e - t; int bl = b.size() > 0 ? b.back() - 2 * t : 0; int sd = st; int ed = et; int bd = (bl + 1 ) / 2; if(sd <= 0 && ed <= 0 && bd <= 0){ break; } if(sd >= ed && sd >= bd){ r += st; s = 0; ++t; } else if (ed >= bd) { r += et; e = 0; ++t; } else { r += bl > 1 ? (bl - 1) : 1; b.pop_back(); t += 2; } } cout << c - r << endl; } int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; for (int i = 0; i < tc; ++i) { solve(i); } return 0; } |