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
// Autor: Mikołaj Janusz
#include <bits/stdc++.h>

typedef long long ll;

using namespace std;

ll calculate_res(vector<ll>& blocks, ll starting_day) {
    ll result = 0;
    for (ll i = 0; i < blocks.size(); i++) {
        ll saved = blocks[i] - (starting_day * 2);
        if (saved <= 0) {
            break;
        } else {
            result += max(saved - 1, 1ll);
            starting_day += 2; 
        }
    }

    return result;
}

int main() {
    ll rounds;
    cin >> rounds;

    for (ll i = 0; i < rounds; i++) {
        ll k, counter = 0, day = 0;
        cin >> k;

        vector<ll> blocks;
        ll first_zeros = -1, ending_zeros = 0;

        for (ll j = 0; j < k; j++) {
            char temp;
            cin >> temp;

            if (temp == '0') {
                counter++;
            } else {
                if (first_zeros == -1) {
                    first_zeros = counter;
                } else {
                    blocks.push_back(counter);
                }
                counter = 0;
            }
        }

        if (counter != 0 && first_zeros != k) {
            ending_zeros = counter;
            counter = 0;
        }

        sort(blocks.begin(), blocks.end(), greater<ll>());
        
        ll no_sides = calculate_res(blocks, 0);
        ll one_side = calculate_res(blocks, 1);
        ll two_sides = calculate_res(blocks, 2);

        cout << (k - max(no_sides, max(one_side + max(first_zeros, ending_zeros), two_sides + (first_zeros + ending_zeros - 1)))) << "\n";
    }
    return 0;
}