#define make_pair mp #define emplace_back pb #include <bits/stdc++.h> using namespace std; mt19937 mt_rand(time(0)); const int N = 1e5 + 5; int t, n; char s[N]; multiset<int> S; int main() { scanf("%d", &t); while(t--) { S.clear(); scanf("%d", &n); scanf("%s", s); int first = 0; while(s[first] == '0') first++; int a = first; if(first == n) { a = -1; } for(int i=first + 1;i<n;i++) { if(s[i] == '1') { if(i != first + 1) S.insert(i - first - 1); first = i; } } int b = n - first - 1; if(first == n) { b = -1; } if(a < b) swap(a, b); int time = 0; int res = 0; S.insert(0); while(true) { auto it = S.end(); it--; int x = *it; if(2 * a >= x) { if(a - time <= 0) break; res += a - time; time++; a = -1; } else if(2 * b >= x) { if(b - time <= 0) break; res += b - time; time++; b = -1; } else { S.erase(it); x -= 2 * time; if(x == 1) { res++; break; } if(x <= 0) { break; } res += x - 1; time += 2; } } if(first == n) { printf("0\n"); } else printf("%d\n", n - res); } 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 | #define make_pair mp #define emplace_back pb #include <bits/stdc++.h> using namespace std; mt19937 mt_rand(time(0)); const int N = 1e5 + 5; int t, n; char s[N]; multiset<int> S; int main() { scanf("%d", &t); while(t--) { S.clear(); scanf("%d", &n); scanf("%s", s); int first = 0; while(s[first] == '0') first++; int a = first; if(first == n) { a = -1; } for(int i=first + 1;i<n;i++) { if(s[i] == '1') { if(i != first + 1) S.insert(i - first - 1); first = i; } } int b = n - first - 1; if(first == n) { b = -1; } if(a < b) swap(a, b); int time = 0; int res = 0; S.insert(0); while(true) { auto it = S.end(); it--; int x = *it; if(2 * a >= x) { if(a - time <= 0) break; res += a - time; time++; a = -1; } else if(2 * b >= x) { if(b - time <= 0) break; res += b - time; time++; b = -1; } else { S.erase(it); x -= 2 * time; if(x == 1) { res++; break; } if(x <= 0) { break; } res += x - 1; time += 2; } } if(first == n) { printf("0\n"); } else printf("%d\n", n - res); } return 0; } |