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

using namespace std;

template <typename T>
std::ostream & operator << (std::ostream & os, const std::vector<T> & vec) {
    for(auto elem : vec)
        os<<elem<< " ";
    return os;
}
void solve() {
    int n;
    cin >> n;

    vector<int> b;

    b.push_back(0); // indeksujemy od 1.
    int j=0;

    char prev = '-';

    string s;
    cin >> s;

    priority_queue<int> extreme;

    int first_one = s.find_first_of('1');
    if (first_one == string::npos) {
        cout << 0 << endl;
        return;
    }
    else
        if (first_one > 0)
            extreme.push(first_one);

    int last_one = s.find_last_of('1');
    if (last_one < s.length() - 1)
        extreme.push(s.length() - 1 - last_one);

    for (int i=first_one; i<last_one; ++i) {
        if (s[i] == '0') {
            if (prev == '1') {
                b.push_back(0);
                ++j;
            }
            b[j]++;
        }
        prev = s[i];
    }

    // cout << "wejsciowy: " <<  b << endl;

    sort (b.begin(), b.end(), greater<int>()); // na koncu strażnik: 0.

    j = 0;
    int t = 0;

    int saved = 0;

    while (true) {
        if (not extreme.empty() and extreme.top() - t > max(0, (b[j] - 2*t) / 2)) {
            saved += extreme.top() - t;
            extreme.pop();
            ++t;
        }
        else if (b[j] - 2*t > 0) {
            saved += (b[j] - 2*t) > 1 ? b[j] - 2*t - 1 : 1;
            j += 1;
            t += 2;
        } else
            break;
    }

    cout << n - saved << endl;

}

int main() {
    int t;
    cin >> t;
    for (int i=0; i<t; ++i)
        solve();
}