//Jakub Rozek
//Pandemia
//czas: sumn*log(sumn)
//pammiec: n
#include "bits/stdc++.h"
using namespace std;
int test,n,x,wyn,p;
bool f;
string s;
priority_queue <int> a,b;
void zmiennaque()
{
while(!a.empty()) a.pop();
while(!b.empty()) b.pop();
x=0;
f=0;
for(int i=0; i<n; ++i)
{
if(s[i]=='1')
{
if(f)
{
if(x) b.push(x);
}
else
{
a.push(x);
f=1;
}
x=0;
}
else ++x;
}
a.push(x);
}
void usuna()
{
p=a.top()-x;
a.pop();
if(p<=0) return;
wyn+=p;
++x;
}
void usunb()
{
p=b.top()-2*x;
b.pop();
if(p<=0) return;
wyn+=1;
p-=1;
a.push(p+x);
++x;
}
void solution()
{
cin>>n>>s;
zmiennaque();
if(a.size()==1)
{
cout<<"0\n";
return;
}
x=0;
wyn=0;
while(!a.empty() || !b.empty())
{
if(a.empty()) usunb();
else if(b.empty()) usuna();
else
{
if(a.top()*2>=b.top()) usuna();
else usunb();
}
}
cout<<n-wyn<<"\n";
return;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>test;
while(test--) solution();
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 | //Jakub Rozek //Pandemia //czas: sumn*log(sumn) //pammiec: n #include "bits/stdc++.h" using namespace std; int test,n,x,wyn,p; bool f; string s; priority_queue <int> a,b; void zmiennaque() { while(!a.empty()) a.pop(); while(!b.empty()) b.pop(); x=0; f=0; for(int i=0; i<n; ++i) { if(s[i]=='1') { if(f) { if(x) b.push(x); } else { a.push(x); f=1; } x=0; } else ++x; } a.push(x); } void usuna() { p=a.top()-x; a.pop(); if(p<=0) return; wyn+=p; ++x; } void usunb() { p=b.top()-2*x; b.pop(); if(p<=0) return; wyn+=1; p-=1; a.push(p+x); ++x; } void solution() { cin>>n>>s; zmiennaque(); if(a.size()==1) { cout<<"0\n"; return; } x=0; wyn=0; while(!a.empty() || !b.empty()) { if(a.empty()) usunb(); else if(b.empty()) usuna(); else { if(a.top()*2>=b.top()) usuna(); else usunb(); } } cout<<n-wyn<<"\n"; return; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>test; while(test--) solution(); return 0; } |
English