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

using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n, t, count = 0, tab[50001] = { 0 }, beg = 0, end = 0, zaszcz = 0, bonus = 0;
    char c, cp;
    cin >> t;
    for (int i = 0; i < t; ++i) {
        cin >> n;
        cin >> c;
        if (c == '0') {
            beg = 1;
            while (beg < n)
            {   
                cin >> c;
                if (c == '0') beg++;
                else break;
            }
        }
        if (beg == n) {
            cout << 0 << endl;
            beg = 0;
            continue;
        }
        for (int j = beg+1; j < n; ++j) {
            cp = c;
            cin >> c;
            if (c == '1') {
                if (j > 0 && cp == '0') count++;
                continue;
            }
            tab[count]++;
        }
        if (c == '0') end = tab[count];
        sort(tab, tab+count, greater<int>());

        for (int j = 0; j < count; ++j) {
            if (beg-j-bonus > 0 && beg >= end && beg-j-bonus >= tab[j]-(2*(j+bonus)+1)) {
                zaszcz += (beg-j-bonus);
                beg = 0;
                bonus++;
            }
            if (end-j-bonus > 0 && end >= beg && end-j-bonus >= tab[j]-(2*(j+bonus)+1)){
                zaszcz += (end-j-bonus);
                end = 0;
                bonus++;
            }
            if (beg-j-bonus > 0 && beg >= end && beg-j-bonus >= tab[j]-(2*(j+bonus)+1)) {
                zaszcz += (beg-j-bonus);
                beg = 0;
                bonus++;
            }
            if (tab[j]-(2*(j+bonus)+1) > 0) { zaszcz += (tab[j]-(2*(j+bonus)+1)); bonus++; }
            else if (tab[j]-(2*(j+bonus)+1) == 0) zaszcz++;
            else break;
        }

        cout << n-zaszcz << endl;

        for (int j = 0; j < count+1; ++j)
            tab[j] = 0;
        bonus = zaszcz = beg = end = count = 0;
    }

    return 0;
}