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
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <bits/stdc++.h>
using namespace std;

int a;
char tab[100007];
int k;
int t;
int p;
int dlg;
int dlg1;
int dlg2;
priority_queue <int> Q;

void solve()
{
    cin >> a;

    k = 0;

    for(int i = 0; i < a; i++)
    {
        cin >> tab[i];

        k += (tab[i] == '1');
    }

    if(k == 0)
    {
        cout << k << endl;

        return;
    }

    dlg1 = 0;
        
    while(tab[dlg1] == '0')
    {
        dlg1++;
    }

    dlg2 = 0;

    while(tab[a - 1 - dlg2] == '0')
    {
        dlg2++;
    }



    for(int i = dlg1; i + dlg2 < a; i++)
    {
        if(tab[i] == '0')
        {
            dlg++;
        }
        else
        {
            if(dlg != 0)
            {
                Q.push(dlg);
            }

            dlg = 0;
        }
    }

    t = 0;

    while(Q.size())
    {
        p = Q.top();
        Q.pop();

        if(p - 2 * t < dlg1 - t)
        {
            Q.push(p);

            k += min(t, dlg1);

            dlg1 = -100000000;

            t += 1;
        }
        else
        {
            if(p - 2 * t < dlg2 - t)
            {
                Q.push(p);

                k += min(t, dlg2);

                dlg2 = -100000000;

                t += 1;
            }
            else
            {
                k += min(2 * t + 1, p);
                
                t += 2;
            }
        }
    }

    cout << k << endl;

    return;
    
}

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

    int t;
    cin >> t;

    for(int i = 0; i < t; i++)
    {
        solve();
    }

    return 0;
}