#include <iostream> #include <string> #include <algorithm> //#include <bits/stdc++.h> using namespace std; int tab[100009] {}; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string s; int t,n,l=-100,p=-100,x=0,mia=0,ix=0,dz=0,k=0,ile=0,mmax=0,nx=0,dx=0; cin>>t; for (int i=0;i<t;i++) { cin>>n>>s; l=-100,p=-100,x=0,mia=0,ix=0,dz=0,k=0,ile=0,mmax=0,nx=0,dx=0; while (x<n) { mia=0; if ((s[x]=='0')) { mia=0; while ((s[x]=='0') && x<n) { mia++; x++;} x--; tab[ix]=mia; ix++; mia=0; } x++; } tab[ix]=-100,tab[ix+1]=-100; if (ix==0) {cout<<n<<"\n"; continue;} if (ix==1 && tab[0]==n) {cout<<"0\n"; continue;} if (s[n-1]=='0') {p=tab[ix-1]; tab[ix-1]=-100;} if (s[0]=='0') {l=tab[0]; tab[0]=-100;} if (p>l) {swap(p,l);} sort (tab,tab+ix); reverse (tab,tab+ix); ix=0,dz=0,ile=0; while (1) { nx=2; mmax=tab[ix]-(2*dz)-1; dx=1; if ((tab[ix]-(2*dz)==1) || (tab[ix]-(2*dz)==2)) {mmax=1; nx=1;} if (l-dz>0) { if (l-dz>(mmax+1)/2) {mmax=l-dz; l=-1000; dx=0; nx=1;} } else if (p-dz>0) { if (p-dz>(mmax+1)/2) {mmax=p-dz; p=-1000; dx=0; nx=1;} } dz=dz+nx; ix=ix+dx; if (mmax<1) {break;} ile=ile+mmax; } cout<<n-ile<<"\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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | #include <iostream> #include <string> #include <algorithm> //#include <bits/stdc++.h> using namespace std; int tab[100009] {}; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string s; int t,n,l=-100,p=-100,x=0,mia=0,ix=0,dz=0,k=0,ile=0,mmax=0,nx=0,dx=0; cin>>t; for (int i=0;i<t;i++) { cin>>n>>s; l=-100,p=-100,x=0,mia=0,ix=0,dz=0,k=0,ile=0,mmax=0,nx=0,dx=0; while (x<n) { mia=0; if ((s[x]=='0')) { mia=0; while ((s[x]=='0') && x<n) { mia++; x++;} x--; tab[ix]=mia; ix++; mia=0; } x++; } tab[ix]=-100,tab[ix+1]=-100; if (ix==0) {cout<<n<<"\n"; continue;} if (ix==1 && tab[0]==n) {cout<<"0\n"; continue;} if (s[n-1]=='0') {p=tab[ix-1]; tab[ix-1]=-100;} if (s[0]=='0') {l=tab[0]; tab[0]=-100;} if (p>l) {swap(p,l);} sort (tab,tab+ix); reverse (tab,tab+ix); ix=0,dz=0,ile=0; while (1) { nx=2; mmax=tab[ix]-(2*dz)-1; dx=1; if ((tab[ix]-(2*dz)==1) || (tab[ix]-(2*dz)==2)) {mmax=1; nx=1;} if (l-dz>0) { if (l-dz>(mmax+1)/2) {mmax=l-dz; l=-1000; dx=0; nx=1;} } else if (p-dz>0) { if (p-dz>(mmax+1)/2) {mmax=p-dz; p=-1000; dx=0; nx=1;} } dz=dz+nx; ix=ix+dx; if (mmax<1) {break;} ile=ile+mmax; } cout<<n-ile<<"\n"; } return 0; } |