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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
//Ada Kołodziejczak
//Zadanie Pandemia
#include<bits/stdc++.h>
#define pb push_back
using namespace std;
int q, n, wyn, l, li, ltb;
int tb[2];//tablica na brzegi
vector<int> v; 
string s;
bool xd;

int main()
{
    ios_base::sync_with_stdio(0);
    cin>>q;

for(int z=0; z<q; ++z)
{
    cin>>n>>s;
    
    v.resize(0);
    xd=0;
    tb[0]=0;
    tb[1]=0;
    wyn=0;
    li=0;
    l=0;
    
    while(s[l]=='0'&&l<n) ++l;
    if(l) tb[0]=l;

    for(int i=l+1; i<n; ++i)
    {
        if(s[i]=='1'&&xd==1)
        {
            v.pb(li);
            xd=0;
            li=0;
        } 
        else if(s[i]=='0')
        {
            ++li;
            xd=1;
        } 
    }

    if(li) tb[1]=li;
    l=0;
    li=0;

    if(v.size()==0)
    {
        if(tb[0]==0&&tb[1]==0) cout<<n<<"\n";
        else if(tb[0]!=0&&tb[1]!=0) cout<<n+1-tb[0]-tb[1]<<"\n";
        else cout<<n-max(tb[0],tb[1])<<"\n";
        continue;
    } 

    sort(v.begin(), v.end());
    if(tb[1]>tb[0]) swap(tb[1],tb[0]);
    l=v.size()-1;
    ltb=0;

    while(l>=0&&(li*2<v[l]||ltb<2))
    {
        if(ltb<2)
        {            
            if(tb[ltb]*2>v[l])
            {
                wyn+=tb[ltb]-li;
                ++li;
                ++ltb;
            }
            else
            {
                if(v[l]-li*2==1||v[l]-li*2==2)
                {
                    wyn+=1;
                    ++li;
                }
                else 
                {
                    wyn+=max(v[l]-li*2-1,0);
                    li+=2;
                }
                --l;
            }
            if(tb[ltb]<li) ++ltb;
        }
        else
        {
            if(v[l]-li*2==1||v[l]-li*2==2)
            {
                wyn+=1;
                ++li;
            }
            else 
            {
                wyn+=max(v[l]-li*2-1,0);
                li+=2;
            }
            --l;
        }
    }

    while(ltb<2)
    {
        if(tb[ltb]>li)
        {
            wyn+=tb[ltb]-li;
            ++li;
        }
        ++ltb;
    }

    cout<<n-wyn<<"\n";
}
}