#include <cstdio> #include <vector> #include <string> #include <algorithm> using namespace std; char s[101013]; int tcase() { int n; scanf("%d %s", &n, s); int pop = -1; vector<int> je(1), dw(1); for (int i = 0; i < n; i++) { if(s[i] == '1') { if (pop == -1) { je.push_back(i); } else { dw.push_back(i - 1 - pop); } pop = i; } } je.push_back(n-1-pop); sort(je.begin(), je.end()); sort(dw.begin(), dw.end()); int t = 0, res = 0; while(je.back() > t || dw.back() > t+t) { if (je.back() * 2 >= dw.back()) { res += je.back() - t; t++; je.pop_back(); } else if (dw.back() - t - t == 1) { res++; t++; dw.pop_back(); } else { res += dw.back() - t-t-1; t += 2; dw.pop_back(); } } return n-res; } int main() { int tt; scanf("%d", &tt); while(tt--) { printf("%d\n",tcase()); } 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 | #include <cstdio> #include <vector> #include <string> #include <algorithm> using namespace std; char s[101013]; int tcase() { int n; scanf("%d %s", &n, s); int pop = -1; vector<int> je(1), dw(1); for (int i = 0; i < n; i++) { if(s[i] == '1') { if (pop == -1) { je.push_back(i); } else { dw.push_back(i - 1 - pop); } pop = i; } } je.push_back(n-1-pop); sort(je.begin(), je.end()); sort(dw.begin(), dw.end()); int t = 0, res = 0; while(je.back() > t || dw.back() > t+t) { if (je.back() * 2 >= dw.back()) { res += je.back() - t; t++; je.pop_back(); } else if (dw.back() - t - t == 1) { res++; t++; dw.pop_back(); } else { res += dw.back() - t-t-1; t += 2; dw.pop_back(); } } return n-res; } int main() { int tt; scanf("%d", &tt); while(tt--) { printf("%d\n",tcase()); } return 0; } |