#include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define s second #define f first #define mp make_pair const long long maxN = 5e5+7; bool cmp(long long a, long long b) { return a>b; } void solve() { long long n; cin>>n; char c,last='1'; vector<long long >vec,rst; bool ok=0; long long zer=0; for (long long i = 0; i < n; i++) { cin>>c; if(c=='0')zer++; else { if(last=='0') { if(zer<=2 && ok) rst.push_back(zer); else if(ok)vec.push_back(zer-1); } if(!ok) rst.push_back(zer); ok=1; zer=0; } last=c; } rst.push_back(zer); long long k=0,ans=0; sort(vec.begin(),vec.end(),cmp); sort(rst.begin(),rst.end(),cmp); for (long long i = 0; i < vec.size(); i++) { if((vec[i]-k*2)<=0) break; ans+=vec[i]-k*2; k+=2; } for (long long i = 0; i < rst.size(); i++) { if((rst[i]-k)<=0)break; ans+=rst[i]-k; k++; } cout<<n-ans<<"\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long t; cin>>t; while(t--)solve(); }
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 | #include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define s second #define f first #define mp make_pair const long long maxN = 5e5+7; bool cmp(long long a, long long b) { return a>b; } void solve() { long long n; cin>>n; char c,last='1'; vector<long long >vec,rst; bool ok=0; long long zer=0; for (long long i = 0; i < n; i++) { cin>>c; if(c=='0')zer++; else { if(last=='0') { if(zer<=2 && ok) rst.push_back(zer); else if(ok)vec.push_back(zer-1); } if(!ok) rst.push_back(zer); ok=1; zer=0; } last=c; } rst.push_back(zer); long long k=0,ans=0; sort(vec.begin(),vec.end(),cmp); sort(rst.begin(),rst.end(),cmp); for (long long i = 0; i < vec.size(); i++) { if((vec[i]-k*2)<=0) break; ans+=vec[i]-k*2; k+=2; } for (long long i = 0; i < rst.size(); i++) { if((rst[i]-k)<=0)break; ans+=rst[i]-k; k++; } cout<<n-ans<<"\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long t; cin>>t; while(t--)solve(); } |