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
#include "bits/stdc++.h" // Ignacy Boehlke
using namespace std;     // XIII LO Szczecin
template<class A, class B> ostream& operator << (ostream& os, const pair<A, B>& p) {return os << '{' << p.first << ", " << p.second << '}';}
template<class T> auto operator << (ostream& os, const T& v) -> decltype(v.begin(), os) {os << '{';for (auto i : v) os << i << ", ";return os << '}';}
#ifdef DEBUG
#define D(x...) x
#else
#define D(x...)
#endif
#define LN(x) D(cerr << #x << ": " << x << ' ')
#define LOG(x) D(cerr << #x << ": " << x << '\n')
#define ssize(x) ((int)x.size())
#define FOR(a, b, c) for(int a = (b); a <= (c); ++a)
#define REP(a, b) FOR(a, 0, b - 1)
#define ALL(x) (x).begin(), (x).end()
#define fi first
#define se second
using ll = long long;

void solve() {
    int n, c = 0, cs = 0;
    scanf("%d ", &n);
    vector<pair<int, bool>> segs;
    REP(i, n) {
        if (getchar() == '1') {
            if (c) segs.emplace_back(c, !cs);
            ++cs;
            c = 0;
        } else ++c;
    }
    if (cs && c) segs.emplace_back(c, true);
    sort(ALL(segs), [&](const auto& a, const auto& b) {return a.fi * (a.se + 1) > b.fi * (b.se + 1);});
    LOG(segs);
    int k = 0;
    REP(i, ssize(segs)) {
        auto [l, t] = segs[i];
        if (t) {
            cs += min(l, k);
            ++k;
        } else {
            if (l == 2 * k + 1 || l == 2 * k + 2) {
                cs += l - 1;
                ++k;
            } else {
                cs += min(l, 2 * k + 1);
                k += 2;
            }
        }
    }

    printf("%d\n", cs);
}

int main() {
    int T;
    scanf("%d", &T);
    while (T--) solve();
}