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

int main() {
    using namespace std;
    int t;
    cin >> t;
    while(t--) {
        int n;
        string A;
        cin >> n >> A;
        vector<int> B, C;
        int c = 0;
        for(int i = 0; i < n; i++) {
            if(A[i] == '0') {
                c += 1;
            } else if(c > 0) {
                B.push_back(c);
                c = 0;
            }
        }
        if(c > 0)
            B.push_back(c);

        if(B.size() == 0) {
            cout << n << "\n";
            continue;
        } else if(B.size() == 1) {
            if(A[0] == '1' && A[n - 1] == '1')
                cout << n - (B[0] - 1) << "\n";
            else
                cout << n - B[0] << "\n";
        } else {
            if(A[n - 1] == '0') {
                C.push_back(B.back());
                B.pop_back();
            }
            if(A[0] == '0') {
                reverse(B.begin(), B.end());
                C.push_back(B.back());
                B.pop_back();
            }
            if(C.size() > 1 && C[0] > C[1])
                swap(C[0], C[1]);

            int time = 0, prot = 0;
            sort(B.begin(), B.end());
            reverse(B.begin(), B.end());

            for(int i = 0; i < B.size(); i++) {
                if (!C.empty() && (2 * (C.back() - time) > B[i] - 2 * time)) { // || 0 >= B[i] - 2 * time)) {
                    if(C.back() - time > 0) {
                        prot += C.back() - time;
                        time += 1;
                    }
                    C.pop_back();
                    i--;
                } else {
                    int left = B[i] - 2 * time;
                    if(left <= 0) continue;
                    if(left == 1 || left == 2) {
                        prot += 1;
                        time += 1;
                        continue;
                    }
                    prot += left - 1;
                    time += 2;
                }
            }
            while(!C.empty()) {
                if(C.back() - time > 0) {
                    prot += C.back() - time;
                    time += 1;
                }
                C.pop_back();
            }
            cout << n - prot << "\n";
        }
    }
    return 0;
}