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

struct classcomp {
  bool operator() (pair<int,int> lhs, pair<int,int> rhs) const
  {
      lhs.first += 2*lhs.second;
      rhs.first += 2*rhs.second;
      return lhs>rhs;
  }
};


void go(string s)
{
    multiset<pair<int,int>, classcomp> ms, ms2;
    //cout << s << endl;
    s += '#';
    string p;
    bool is_first = true;
    int j = 0;
    for(int i=0; i<s.size()-1; ++i)
    {
        if(s[i]=='1') ++j;
        pair<int,int> z;
        p += s[i];
        if(s[i]!=s[i+1])
        {
            if(is_first)
            {
                if(p[0]=='0')
                {
                    z.second = 1;
                }
                is_first = false;
            }
            z.first = p.size();
            if(s[i+1]=='#')
            {
                if(p[0]=='0')
                {
                    z.second = 1;
                }
            }
            if(p[0]=='0')
            {
                ms.insert(z);
            }
            p = "";
        }
    }

    int res = 0;
    while(!ms.empty())
    {
        ms2.clear();
        bool is_first = true;
        for(auto x:ms)
        {
            //cout << "(" << x.first << "," << x.second << ")" << endl;
            if(is_first)
            {
                x.second += 1;
                x.first  -= 1;
                is_first = false;
            }
            if(x.second<2)
            {
                x.first -= 2-x.second;
                res += 2-x.second;
                if(x.first<0) res -= 1; // korekta
                //cout << "po odjeciu " << x.first << "," << x.second << endl;

                if(x.first>0)
                    ms2.insert(x);
            }
        }
        ms = ms2;
        //cout << string(10,'-') << endl; system("pause");
    }
    cout << res+j << "\n";
    //cout << string(10,'=') << endl;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);

    int t; cin >> t;
    for(int i=0; i<t; ++i)
    {
        int n; cin >> n;
        string s; cin >> s;
        go(s);
    }
    cout << flush;
}