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

const int N = int(5e5) + 99;

int n, x, k;
char c;
int a[N];

int solve() {
    
    cin >> n;
    vector<int> intervals = {0};
    vector<int> slow_intervals = {0};
    int count = 0;
    for (int i = 0; i < n; i++) {
        cin >> c;
        if (c == '1') {
            if (slow_intervals.size() == 1) {
                slow_intervals.push_back(count); 
            } else {
                intervals.push_back(count);
            }
            count = 0;
        } else {
            count++;
        }
    }
    if (slow_intervals.size() == 1) {
        return 0;
    }
    slow_intervals.push_back(count);
    int healthy = 0;
    int round = -1;

    sort(intervals.begin(), intervals.end());
    sort(slow_intervals.begin(), slow_intervals.end());

    // for (auto i : slow_intervals) {
    //     cout << i << " ";
    // }
    // cout << endl;


    int slow_offset = 0, offset = 0;
    int curr, curr_slow;
    while (true) {
        round++;
        curr = intervals.back() - round * 2;
        curr_slow = slow_intervals.back() - round;

        // cout << "ROUND:" << round << endl;
        // cout << "curr:" << curr << endl;
        // cout << "curr_slow:" << curr_slow << endl;
        // cout << "healthy:" << healthy << endl;
        // cout << slow_intervals.back() << endl;

        if (curr <= 0 && curr_slow <= 0) break;
        if (curr > curr_slow) {
            healthy++;
            slow_intervals.push_back(intervals.back() - round - 1);
            intervals.pop_back();
        } else {
            healthy += curr_slow;
            slow_intervals.pop_back();
        }
    }

    return n-healthy;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin >> t;
    for (int i = 0; i < t; i++) {
        cout << solve() << endl;
    }
}