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
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;

struct Inter
{
    int x;
    int len;
    int ends;
};

bool comp(Inter a, Inter b)
{
    if(a.x==b.x && a.ends==b.ends)return a.len>b.len;
    else if(a.x==b.x)return a.ends<b.ends;
    return a.x>b.x;
}

void solve()
{
    int n;
    cin>>n;
    string s;
    cin>>s;
    int len=0;
    int res=0;
    bool bg=true;
    vector<Inter> V;
    for(char x: s)
    {
        if(x=='0')len++;
        else
        {
            res++;
            if(bg && len)V.push_back({len, len, 1});
            else if(len)V.push_back({(len+1)/2, len, 2});
            len=0;
            bg=false;
        }
    }

    if(len==n)
    {
        cout<<"0"<<endl;
        return;
    }
    if(len)V.push_back({len, len, 1});
    sort(V.begin(), V.end(), comp);

    int t=0;
    for(Inter u: V)
    {
  //      cout<<u.x<<u.len<<u.ends<<endl;
        if(t<u.x)
        {
            if(u.ends==1)
            {
                res+=t;
                t++;
            }
            else
            {
                if(t+1==u.x)
                {
                    if(u.len%2)res+=2*t;
                    else res+=2*t+1;
                    t++;
                }
                else
                {
                    res+=2*t+1;
                    t+=2;
                }
            }
        }
        else res+=u.len;
   //     cout<<res<<endl;
    }
    cout<<res<<endl;
}

int main()
{
    ios_base::sync_with_stdio(0);
    int Z;
    cin>>Z;
    while(Z--)solve();
}