#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define p_b push_back
#define m_p make_pair
#define fi first
#define se second
ll inf = 8000000000000000000;
ll mod = 30000;
const int maxn = 200003;
bool cmp(int a, int b){
return abs(a)>abs(b);
}
int main(){
ios_base::sync_with_stdio(0);
int z; cin>>z;
while(z--){
int n; cin>>n;
string s; cin>>s;
vector<int> t1;
int ost = -1;
for(int i = 0; i<n; i++)
if(s[i]=='1'){
if(ost==-1)
t1.p_b(-(i-ost-1)*2);
else
t1.p_b(i-ost-1);
ost = i;
}
t1.p_b(-(n-ost-1)*2);
sort(t1.begin(), t1.end(), cmp);
int res = 0, ti = 0;
for(int i = 0; i<(int)t1.size(); i++){
//cout<<t1[i]<<" "<<res<<" "<<ti<<endl;
if(t1[i]<0){
int d = -t1[i]/2-ti;
if(d<=0) continue;
res += max(0, d);
ti++;
}
else{
int d = t1[i]-ti*2;
if(d<=0) continue;
if(d<=1) res += max(0, d);
else res += max(0, d-1);
if(d<=2) ti++;
else ti += 2;
}
}
cout<<n-res<<"\n";
}
}
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 | #include <bits/stdc++.h> using namespace std; #define ll long long #define p_b push_back #define m_p make_pair #define fi first #define se second ll inf = 8000000000000000000; ll mod = 30000; const int maxn = 200003; bool cmp(int a, int b){ return abs(a)>abs(b); } int main(){ ios_base::sync_with_stdio(0); int z; cin>>z; while(z--){ int n; cin>>n; string s; cin>>s; vector<int> t1; int ost = -1; for(int i = 0; i<n; i++) if(s[i]=='1'){ if(ost==-1) t1.p_b(-(i-ost-1)*2); else t1.p_b(i-ost-1); ost = i; } t1.p_b(-(n-ost-1)*2); sort(t1.begin(), t1.end(), cmp); int res = 0, ti = 0; for(int i = 0; i<(int)t1.size(); i++){ //cout<<t1[i]<<" "<<res<<" "<<ti<<endl; if(t1[i]<0){ int d = -t1[i]/2-ti; if(d<=0) continue; res += max(0, d); ti++; } else{ int d = t1[i]-ti*2; if(d<=0) continue; if(d<=1) res += max(0, d); else res += max(0, d-1); if(d<=2) ti++; else ti += 2; } } cout<<n-res<<"\n"; } } |
English