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


void solve() {
    int n, length = 0, saved = 0;
    int b = 0;
    char c;
    multiset<int> opened; // len -> (begin, end)
    multiset<int> closed;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> c;
        if (c == '1' && length > 0) {
            if (b == 0)
                opened.insert(length);
            else
                closed.insert(length);
            length = 0;
        }
        if (c == '0') {
            if (length == 0) {
                b = i;
            }
            length++;
        }
    }
    if (c == '0') {
        opened.insert(length);
    }
    if (opened.size() == n) {
        cout << "0\n";
        return;
    }
    while (opened.size() > 0 || closed.size() > 0) {
        if (closed.size() > 0 && (opened.empty() || *closed.rbegin() > *opened.rbegin() + 2)) {
            // 1 vaccine in closed
            saved += 1;
            // move to opened
            opened.insert(*closed.rbegin() - 1);
            closed.erase(std::prev(closed.end()));
        } else {
            // 1 vaccine in opened
            saved += *opened.rbegin();
            // remove
            opened.erase(std::prev(opened.end()));
        }
        // progress one day through intervals
        auto tmp1 = multiset<int>();
        auto tmp2 = multiset<int>();
        // closed
        for (const auto & el: closed) {
            if (el > 2)
                tmp1.insert(el - 2);
        }
        closed = std::move(tmp1);
        // opened
        for (const auto & el: opened) {
            if (el > 1)
                tmp2.insert(el - 1);
        }
        opened = std::move(tmp2);
    }
    cout << n - saved << "\n";
}

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