#include <bits/stdc++.h> using namespace std; typedef long long ll; #ifdef LOCAL #define debug(...) __VA_ARGS__ #else #define debug(...) {} #endif void solve(){ int i; int n; cin>>n; string s; cin>>s; vector<pair<int,bool> > pq; int akt = 0; for (i = 0; i < n; i++){ if (s[i] == '0') akt++; else{ if (!akt) continue; if (akt == i) pq.push_back({2*akt,1}); else pq.push_back({akt,0}); akt = 0; } } if (akt){ if (akt == n){ cout<<0<<"\n"; return; } pq.push_back({2*akt,1}); } stable_sort(pq.begin(),pq.end()); int d = 0; int wy = 0; for (i = int(pq.size())-1; i > -1; i--){ if (pq[i].second){ //cout<<d<<" "<<pq[i].first/2<<"\n"; if ((pq[i].first/2) < d) continue; wy += (pq[i].first/2)-d; d++; }else{ //cout<<d<<" "<<pq[i].first<<"\n"; if (pq[i].first < 2*d+1) continue; else if (pq[i].first < 2*d+3){ wy++; d++; }else{ wy += pq[i].first-2*d-1; d += 2; } } } cout<<n-wy<<"\n"; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin>>t; while (t--) solve(); 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 | #include <bits/stdc++.h> using namespace std; typedef long long ll; #ifdef LOCAL #define debug(...) __VA_ARGS__ #else #define debug(...) {} #endif void solve(){ int i; int n; cin>>n; string s; cin>>s; vector<pair<int,bool> > pq; int akt = 0; for (i = 0; i < n; i++){ if (s[i] == '0') akt++; else{ if (!akt) continue; if (akt == i) pq.push_back({2*akt,1}); else pq.push_back({akt,0}); akt = 0; } } if (akt){ if (akt == n){ cout<<0<<"\n"; return; } pq.push_back({2*akt,1}); } stable_sort(pq.begin(),pq.end()); int d = 0; int wy = 0; for (i = int(pq.size())-1; i > -1; i--){ if (pq[i].second){ //cout<<d<<" "<<pq[i].first/2<<"\n"; if ((pq[i].first/2) < d) continue; wy += (pq[i].first/2)-d; d++; }else{ //cout<<d<<" "<<pq[i].first<<"\n"; if (pq[i].first < 2*d+1) continue; else if (pq[i].first < 2*d+3){ wy++; d++; }else{ wy += pq[i].first-2*d-1; d += 2; } } } cout<<n-wy<<"\n"; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin>>t; while (t--) solve(); return 0; } |