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
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void test() {
    int n, gapLen{};
    vector<pair<int, int>> gaps;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        char c;
        cin >> c;
        if (c == '1') {
            if (gapLen != 0) {
                gaps.emplace_back(gapLen, 1 + (i != gapLen));
                gapLen = 0;
            }
        } else {
            ++gapLen;
        }
    }
    if (gapLen != 0) {
        gaps.emplace_back(gapLen, 1);
    }

    if (size(gaps) == 1 && gaps[0].first == n) {
        cout << 0 << '\n';
        return;
    }
    sort(begin(gaps), end(gaps), [](pair<int, int> p1, pair<int, int> p2) {
        return p1.first / p1.second > p2.first / p2.second;
    });
    int round{}, safeNo{};
    for (auto gap: gaps) {
        int remainingLen = gap.first - round * gap.second;
        if (remainingLen <= 0) {
            break;
        }
        if (gap.second == 2) {
            if (remainingLen < 3) {
                ++safeNo;
                break;
            }
            safeNo += remainingLen - 1;
            round += 2;
        } else {
            safeNo += remainingLen;
            ++round;
        }
    }
    cout << n - safeNo << '\n';
}

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