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
83
84
85
86
87
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<algorithm>
#include<vector>



using namespace std;

int main()
{
    std::ios_base::sync_with_stdio(false);
    vector<int> lista;
    int sides[2];
    int  n, ones = 0;
    int t, sum;
    char a, prev;
    cin >> t;
    for (int j = 0; j < t; j++) {
        lista.clear();
        prev = '0';
        sum = 0;
        sides[0] = 0;
        sides[1] = 0;
        cin >> n; 
        for (int i = 0; i < n; i++) {
            cin >> a;
            if (a == '0') {
                sum++;
            }
            else if (a != prev) {
                lista.push_back(sum);
                sum = 0;
            }
            prev = a;
        }
        if (sum > 0) {
            sides[0] = sum;
        }
        int size = lista.size();
        if (size > 0) {
            sides[1] = lista[0];
        }
        else {
            cout << n - sides[0] << '\n';
            continue;
        }
        sort(lista.begin() + 1, lista.end());
        int spread = 0;
        int saved = 0;
        int ptr = size - 1;
        int cur_val = lista[ptr] - 2 * spread - 1;
        while (ptr > 0 && cur_val > 0) {
            if (cur_val >= 2*(sides[0] - spread) && cur_val >= 2*(sides[1] - spread)) {
                spread += 2;
                ptr--;
                saved += cur_val;
            }
            else {
                if (sides[0] > sides[1]) {
                    saved += sides[0]-spread;
                    sides[0] = 0;
                }
                else {
                    saved += sides[1]-spread;
                    sides[1] = 0;
                }
                spread++;

            }
            cur_val = lista[ptr] - 2 * spread - 1;
        }
        if (cur_val == 0 && sides[0] - spread == 0 && sides[1] - spread == 0) {
            saved++;
        }
        if (sides[0] - spread > 0) {
            saved += sides[0] - spread;
            spread++;
        }
        if (sides[1] -spread > 0) {
            saved += sides[1] - spread;
        }

        cout << n - saved << '\n';
    }
    return 0;
}