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
#include <cstdio>
#include <cassert>
#include <vector>
#include <algorithm>

using namespace std;

typedef pair<int, int> PII;

PII a[3];

PII f_(const vector<int> &s, int t) {
    int res = 0;
    for (auto it = s.begin(); it != s.end(); it++) {
        res += min(2 * t, *it);
        int cur = max(0, *it - 2 * t);
        if (cur == 0) {}
        else if (cur == 1) {
            t++;
        }
        else if (cur == 2) {
            res++;
            t++;
        }
        else if (cur > 2) {
            res++;
            t += 2;
        }
    }
    return PII(res, t);
}

PII f(const vector<int> &_, PII curr) {
    int res = curr.first;
    int t = curr.second;
    auto tmp = a[curr.second];
    res += tmp.first;
    t += tmp.second;
    return PII(res, t);
}

PII g(int edge, PII curr) {
    int res = curr.first;
    int t = curr.second;

    res += min(edge, t);
    edge = max(0, edge - t);
    if (edge > 0) {
        t++;
    }
    return PII(res, t);
}

int solve() {
    int n;
    scanf("%d\n", &n);
    int ones = 0;

    int left = 0, right = 0;
    int prev = -1;
    vector<int> s;

    for (int i = 0; i < n; i++)
    {
        char c;
        scanf("%c", &c);

        if (c == '0') continue;
        ones++;

        if (prev == i - 1) { }
        else if (prev == -1) left = i;
        else s.push_back((i - prev - 1));
        prev = i;
    }

    if (prev == -1) return 0;
    else if (ones == n) return n;
    if (prev != n - 1) right = n - prev - 1;

    sort(s.begin(), s.end());
    reverse(s.begin(), s.end());

    for (int i = 0; i < 3; i++) a[i] = f_(s, i);

    int res = n;

    auto tmp = PII(0, 0);
    tmp = g(right, g(left, f(s, tmp)));
    res = min(res, tmp.first);

    tmp = PII(0, 0);
    tmp = g(left, g(right, f(s, tmp)));
    res = min(res, tmp.first);

    tmp = PII(0, 0);
    tmp = g(left, f(s, g(right, tmp)));
    res = min(res, tmp.first);

    tmp = PII(0, 0);
    tmp = g(right, f(s, g(left, tmp)));
    res = min(res, tmp.first);

    tmp = PII(0, 0);
    tmp = f(s, g(left, g(right, tmp)));
    res = min(res, tmp.first);

    tmp = PII(0, 0);
    tmp = f(s, g(right, g(left, tmp)));
    res = min(res, tmp.first);

    return res + ones;
}

int main() {
    int t;
    scanf("%d\n", &t);
    for (int i = 0; i < t; i++) {
        printf("%d\n", solve());
    }
}