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
88
89
90
91
// Karol Kosinski 2021
#include <bits/stdc++.h>
// #define ENABLE_DEBUG
#define FOR(i,a,b) for(int i=(a),_b=(b);i<_b;++i)
#define FR_(i,a,b) for(int i=(a),_b=(b);i<=_b;++i)
#define FD_(i,b,a) for(int i=(b),_a=(a);i>=_a;--i)
#define ALL(c) (c).begin(),(c).end()
#define SIZE(c) int((c).size())
#define TIE(x...) int x;tie(x)
#define X first
#define Y second
#ifndef ENABLE_DEBUG
#define DEB(k,f,x...)
#else
#define DEB(k,f,x...) {if(k)printf("--------%4d : %s\n",__LINE__,__FUNCTION__);f(x);}
#endif
#define DEBL DEB(1,void,0)
#define DEBF(f,x...) DEB(1,f,x)
#define DEBUG(x...) DEB(0,printf,x)
using namespace std;
using LL = long long;
using ULL = unsigned long long;
using PII = pair<int, int>;
using TIII = tuple<int, int, int>;

constexpr int NX = 100'005;

char T[NX];
vector<PII> Zero;

void testcase()
{
    int n, curlen = 0, time = 0, sum = 0;
    scanf("%d%s", &n, T);
    bool oneside = true;
    FOR(i,0,n)
    {
        if ( T[i] == '0' )
        {
            ++ curlen;
        }
        else
        {
            if (oneside) Zero.emplace_back( 2 * curlen, 2 );
            else Zero.emplace_back( curlen, 1 );
            oneside = false;
            curlen = 0;
            ++ sum;
        }
    }
    Zero.emplace_back( 2 * curlen, 2 );
    sort( ALL(Zero), greater<PII>() );
    for ( const auto& it : Zero )
    {
        DEBUG("(%d, %d)\n", it.X, it.Y);
        if ( it.Y == 2 )
        {
            int aux = min( it.X / 2, time);
            DEBUG("* %d\n", aux);
            sum += aux;
            ++ time;
        }
        else
        {
            int aux = min( it.X, 2 * time);
            DEBUG("* %d\n", aux);
            sum += aux;
            if ( it.X > 2 * time + 1 )
            {
                DEBUG("* 1\n", aux);
                ++ sum;
                time += 2;
            }
            else if ( it.X == 2 * time + 1 )
            {
                ++ time;
            }
        }
    }
    Zero.clear();
    printf("%d\n", sum);
}

int main()
{
    int z;
    scanf("%d", &z);
    Zero.reserve(NX);
    while (z--) testcase();
    return 0;
}