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

int main() {
    std::ios::sync_with_stdio(false);
    int t;
    std::cin >> t;
    while (t--) {
        int n;
        std::cin >> n;

        std::string s;
        std::cin >> s;

        std::vector<int> v;
        int sum = 0;
        for (int i = 0; i < n ; ++i) {
            if (s[i] == '1') {
                v.push_back(sum);
                sum = 0;
            } else sum += 1;
        }
        v.push_back(sum);

        if (v.size() == 1) {
            std::cout << 0 << '\n';
            continue;
        }

        int edge_g = std::max(v[0], v[v.size() - 1]);
        int edge_l = std::min(v[0], v[v.size() - 1]);
        v.erase(v.begin());
        v.pop_back();

        std::sort(v.begin(), v.end());

        int best = n;
        for (int i = 0; i <= 2; ++i) {
            int res = 0;
            int time = 0;
            if (i == 1) {
                res += edge_g;
                time += 1;
            } else if ((i == 2) && (edge_l > 1)) {
                res += edge_g + edge_l - 1;
                time += 2;
            }

            for (int k = v.size() - 1; k >= 0; --k) {
                int val = v[k] - time * 2;
                if (val <= 0) break;

                if (val <= 2) {
                    res += 1;
                    time += 1;
                } else {
                    res += val - 1;
                    time += 2;
                }
            }
            best = std::min(best, n - res);
        }

        std::cout << best << '\n';
    }

    return 0;
}