#include <bits/stdc++.h>
using namespace std;
priority_queue <int> J, D;
void wyczysc () {
while (!J.empty()) J.pop();
while (!D.empty()) D.pop();
}
/*
3
8
00110100
10
1001000010
4
0000
*/
int wczytaj() {
int n; cin>>n;
string s; cin>>s;
int it, it2;
for (it=0; it<n; ++it)
if (s[it]=='1')
break;
if (it == n) return 0;
if (it>0)
J.push(it);
for (it2 = n-1; it2>=it; --it2)
if (s[it2]=='1')
break;
if (n-it2-1>0)
J.push(n-it2-1);
if (it == it2) return 2;
int cnt=0;
for (int i=it; i<=it2; ++i) {
if (s[i]=='1') {
if (cnt!=0) {
D.push(cnt);
cnt = 0;
}
}
else cnt++;
}
if (cnt>0)
D.push(cnt);
return n;
}
int solve (int n) {
if (n==0) return 0;
int sz = 0;
for (int i=0; i<n; ++i) {
if ((D.empty() || D.top()-2*i<=0) && (J.empty() || J.top()-i<=0)) break;
if (!D.empty() && D.top()-2*i>0 && (J.empty() || D.top()-i*2>J.top()-i)) {
J.push(D.top()-i-1);
D.pop();
sz++;
}
else {
sz += J.top()-i;
J.pop();
}
}
return n-sz;
}
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
int t; cin>>t;
while (t--) {
int k = wczytaj();
cout<<solve(k)<<'\n';
wyczysc();
}
}
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 82 83 84 85 | #include <bits/stdc++.h> using namespace std; priority_queue <int> J, D; void wyczysc () { while (!J.empty()) J.pop(); while (!D.empty()) D.pop(); } /* 3 8 00110100 10 1001000010 4 0000 */ int wczytaj() { int n; cin>>n; string s; cin>>s; int it, it2; for (it=0; it<n; ++it) if (s[it]=='1') break; if (it == n) return 0; if (it>0) J.push(it); for (it2 = n-1; it2>=it; --it2) if (s[it2]=='1') break; if (n-it2-1>0) J.push(n-it2-1); if (it == it2) return 2; int cnt=0; for (int i=it; i<=it2; ++i) { if (s[i]=='1') { if (cnt!=0) { D.push(cnt); cnt = 0; } } else cnt++; } if (cnt>0) D.push(cnt); return n; } int solve (int n) { if (n==0) return 0; int sz = 0; for (int i=0; i<n; ++i) { if ((D.empty() || D.top()-2*i<=0) && (J.empty() || J.top()-i<=0)) break; if (!D.empty() && D.top()-2*i>0 && (J.empty() || D.top()-i*2>J.top()-i)) { J.push(D.top()-i-1); D.pop(); sz++; } else { sz += J.top()-i; J.pop(); } } return n-sz; } int main () { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin>>t; while (t--) { int k = wczytaj(); cout<<solve(k)<<'\n'; wyczysc(); } } |
English