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

using namespace std;

int main() {
    int t;
    int n;
    string str;
    vector<int> v;
    cin >> t;
    for (int i=0; i<t; i++) {
        cin >> n;
        cin >> str;
        v.clear();
        int sec {};
        bool first {true};
        int v1 {};
        int v2 {};
        for (int j=0; j<n; j++) {
            if (str[j] == '1') {
                if (sec > 0) {
                    if (first) {
                        v1 = sec;
                    } else {
                        v.push_back(sec);
                    }
                }
                sec = 0;
                first = false;
            } else {
                sec++;
            }
        }
        if (sec > v1) {
            v2 = v1;
            v1 = sec;
        } else {
            v2 = sec;
        }
        sort(v.begin(), v.end(), greater<int>());
        int res {};
        int time {};
        auto it {v.begin()};
        while (v1 > time || it != v.end() && *it > time*2) {
            if (it == v.end() || v1-time >= *it - time*2) {
                res += v1 - time;
                v1 = v2;
                v2 = 0;
            } else {
                res += max(*it - time*2 -1, 1);
                it++;
                time++; 
            }
            time++;
        }
        cout << n-res << endl;
    }
    return 0;
}