#include<bits/stdc++.h>
using namespace std;
int n;
string str;
priority_queue <int> Qjedno, Qdwu;
int pocz(){
int wynik=0;
for(int i=0; i<n; i++){
if(str[i]=='0')wynik++;
else break;
}
if(wynik!=0)Qjedno.push(wynik);
return wynik;
}
int kon(){
int wynik=0;
for(int i=n-1; i>=0; i--){
if(str[i]=='0')wynik++;
else break;
}
if(wynik!=0) Qjedno.push(wynik);
return n-wynik;
}
int solve(){
int ile1=0, ilezer=0; Qjedno.push(0); Qdwu.push(0);
int p=pocz();
if(p==n)return 0;
int k=kon();
for(int i=p; i<k; i++){
if(str[i]=='1'){
ile1++;
if(ilezer>0){
Qdwu.push(ilezer);
ilezer=0;
}
}else{
ilezer++;
}
}
int urat=0, pom;
for(int i=0; i<n; i++){
if(Qdwu.top()-2*i<=0 && Qjedno.top()-i<=0)return n-urat;
if( Qdwu.top()-2*i-1 >= Qjedno.top()-i ){
pom=Qdwu.top()-i-1;
Qdwu.pop();
urat++;
//cout<<urat<<" ";
Qjedno.push(pom);
}
else
{
urat+=Qjedno.top()-i;
//cout<<urat<<" ";
Qjedno.pop();
}
}
//cout<<endl;
}
int main(){
std::ios_base::sync_with_stdio(0);
int q;
cin>>q;
while(q--){
cin>>n;
cin>>str;
cout<<solve()<<"\n";
}
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | #include<bits/stdc++.h> using namespace std; int n; string str; priority_queue <int> Qjedno, Qdwu; int pocz(){ int wynik=0; for(int i=0; i<n; i++){ if(str[i]=='0')wynik++; else break; } if(wynik!=0)Qjedno.push(wynik); return wynik; } int kon(){ int wynik=0; for(int i=n-1; i>=0; i--){ if(str[i]=='0')wynik++; else break; } if(wynik!=0) Qjedno.push(wynik); return n-wynik; } int solve(){ int ile1=0, ilezer=0; Qjedno.push(0); Qdwu.push(0); int p=pocz(); if(p==n)return 0; int k=kon(); for(int i=p; i<k; i++){ if(str[i]=='1'){ ile1++; if(ilezer>0){ Qdwu.push(ilezer); ilezer=0; } }else{ ilezer++; } } int urat=0, pom; for(int i=0; i<n; i++){ if(Qdwu.top()-2*i<=0 && Qjedno.top()-i<=0)return n-urat; if( Qdwu.top()-2*i-1 >= Qjedno.top()-i ){ pom=Qdwu.top()-i-1; Qdwu.pop(); urat++; //cout<<urat<<" "; Qjedno.push(pom); } else { urat+=Qjedno.top()-i; //cout<<urat<<" "; Qjedno.pop(); } } //cout<<endl; } int main(){ std::ios_base::sync_with_stdio(0); int q; cin>>q; while(q--){ cin>>n; cin>>str; cout<<solve()<<"\n"; } return 0; } |
English