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
#include <bits/stdc++.h>
using namespace std;
int t, n, p, it, p0, p1;
char c;
bool b;
vector < int > v;
int main()
{
    scanf("%d", &t);
    for (int j = 0; j < t; ++j)
    {
        scanf("%d%c", &n, &c);
        for (int i = 0; i < n; i++)
        {
            scanf("%c", &c);
            if(c == 49)
            {
                it = i;
                break;
            }
            else if(i == n - 1)
            {
                printf("0");
                b = 1;
            }
        }
        if(b)
        {
            b = 0;
            continue;
        }
        p0 = it;
        p1 = 0;
        for (int i = it + 1; i < n; i++)
        {
            scanf("%c", &c);
            if(c == '1')
            {
                if(p1 != 0)
                    v.push_back(p1);
                p1 = 0;
                continue;
            }
            ++p1;
        }
        it = 0;
        p = 0;
        if(p1 > p0)
            swap(p0, p1);
        sort(v.begin(), v.end(), greater < int > ());
        if(p0 >= v[0])
        {
            p += p0;
            p0 = p1;
            p1 = 0;
            ++it;
        }
        if(p0 - it >= v[0] - 2 * it)
        {
            p += p0 - it;
            p0 = p1;
            p1 = 0;
            ++it;
        }
        for (int i = 0; i < v.size() && v[i] > it * 2; i++)
        {
            if(v[i] - 2 * it <= 3 && p0 - it > 0)
            {
                p += p0 - it;
                p0 = p1;
                p1 = 0;
                ++it;
                --i;
                continue;
            }
            if(p0 - it >= v[i] - 2 * it && p0 - it > 0 )
            {
                p += p0 - it;
                p0 = p1;
                p1 = 0;
                ++it;
                --i;
                continue;
            }
            if(v[i] - 2 * it < 3)
            {
                ++p;
                break;
            }
            p += v[i] - it * 2 - 1;
            it += 2;
        }
        if(p0 > it)
        {
            p += p0 - it;
            ++it;
        }
        p += max(p1 - it, 0);
        v.clear();
        printf("%d\n", n - p);
    }
}