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
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

vector<int> avail1, avail2;

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

    int t, n;
    char c;
    int last_one, len, res;
    int time, m1, m2, g1, g2, c2;
    cin >> t;
    for(int ti = 0; ti < t; ti++) {
        avail1.clear();
        avail2.clear();
        last_one = 0;

        cin >> n;
        for(int i = 1; i <= n; i++) {
            cin >> c;
            if(c == '1') {
                len = i-last_one-1;
                if(last_one == 0)
                    avail1.push_back(len);
                else if(len >= 1)
                    avail2.push_back(len);
                last_one = i;
            }
        }
        if(last_one != 0) {
            avail1.push_back(n-last_one);
        }
        else {
            cout << "0\n";
            continue;
        }

        sort(avail1.begin(), avail1.end());
        sort(avail2.begin(), avail2.end());

        m1 = avail1.size()-1;
        m2 = avail2.size()-1;
        time = 0;
        res = 0;
        g1 = g2 = -1;
        c2 = 1;
        while(true) {
            if(m1 >= 0) {
                g1 = avail1[m1] - time;
            }
            if(g1 <= 0) {
                m1 = -1;
                g1 = -1;
            }
            
            if(m2 >= 0) {
                g2 = avail2[m2] - 2*time;
                if(g2 == 1) {
                    g2 = 1;
                    c2 = 1;
                }
                else {
                    g2--;
                    c2 = 2;
                }
            }
            if(g2 <= 0) {
                m2 = -1;
                g2 = -1;
                c2 = 1;
            }

            if(m1 < 0 and m2 < 0)
                break;
            else if(m1 < 0) {
                res += g2;
                time += c2;
                m2--;
            }
            else if(m2 < 0 or ((double)g1 > (double)g2/c2)) {
                res += g1;
                time++;
                m1--;
            }
            else {
                if((double)g2/c2 >= (double)g1) {
                    res += g2;
                    time += c2;
                    m2--;
                }
                else {
                    res += g1;
                    time++;
                    m1--;
                }
            }
        }
        cout << n - res << "\n";
    }

    return 0;
}