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
// Project: pan
#include <bits/stdc++.h>
using namespace std;

int m;

bool cmp(pair<int, int> &a, pair<int, int> &b) {
	if(a.first == b.first) return a.second > b.second;
    return a.first < b.first;
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin >> m;

    while (m--) {
        int n;
        cin >> n;
        int cl = 0;
        bool an = 0;
        vector<pair<int, int>> v;

        int mxl = 0;

        for (int i = 0; i < n; i++) {
            char a;
            cin >> a;
            if (a == '0') {
                cl++;
            } else {
                if (cl) {
                    mxl = max(mxl, cl);
                    v.emplace_back(cl, 1 + an);
                    cl = 0;
                }
                an = 1;
            }
        }
        if (!an) {
            cout << 0 << '\n';
            continue;
        }

        if (cl) {
            v.emplace_back(cl, 1);
            mxl = max(mxl, cl);
        }


        int saved = 0;


        while (v.size()) {
            sort(v.begin(), v.end(), cmp);
            auto p = *(v.end() - 1);
            v.pop_back();
            saved++;
            p.first--;
            p.second--;
            if (p.second && p.first)
                v.push_back(p);
            else
                saved += p.first;

            for (int i = 0; i < v.size(); i++) {
                v[i].first -= v[i].second;
            }

            for (int i = 0; i < v.size(); i++) {
                if (v[i].first <= 0 || v[i].second <= 0) {
                    saved += max(v[i].first, 0);
                    v.erase(v.begin() + i);
                    i--;
                }
            }
        }

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