#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ int z; cin>>z; while(z--){ int n; cin>>n; string a; cin>>a; int c = 0; vector<pair<int, int>> V; for(int i=0; i<n; i++){ if(a[i]=='0') c++; if(a[i]=='1'&&c>0){ if(i-c==0) V.push_back({c, 1}); else V.push_back({c, 0}); c=0; } } if(a[n-1]=='0') V.push_back({c, 1}); sort(V.rbegin(), V.rend()); int sz = 0; int aa = 0; for(int i=0; i<V.size(); i++){ if(V[i].second==1 && V[i].first - 1*i>=0) sz += V[i].first - 1*i; if(V[i].second==0){ if(V[i].first - 2*(i+aa) == 1) sz+=V[i].first - 2*(i+aa); else if(V[i].first - 2*(i+aa) - 1>=0) sz+=V[i].first - 2*(i+aa) - 1; aa++; } } cout<<n-sz<<endl; } 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 | #include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ int z; cin>>z; while(z--){ int n; cin>>n; string a; cin>>a; int c = 0; vector<pair<int, int>> V; for(int i=0; i<n; i++){ if(a[i]=='0') c++; if(a[i]=='1'&&c>0){ if(i-c==0) V.push_back({c, 1}); else V.push_back({c, 0}); c=0; } } if(a[n-1]=='0') V.push_back({c, 1}); sort(V.rbegin(), V.rend()); int sz = 0; int aa = 0; for(int i=0; i<V.size(); i++){ if(V[i].second==1 && V[i].first - 1*i>=0) sz += V[i].first - 1*i; if(V[i].second==0){ if(V[i].first - 2*(i+aa) == 1) sz+=V[i].first - 2*(i+aa); else if(V[i].first - 2*(i+aa) - 1>=0) sz+=V[i].first - 2*(i+aa) - 1; aa++; } } cout<<n-sz<<endl; } return 0; } |