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

using namespace std;

vector<int> m2;

int foo(int emin, int emax) {
    int cycle = 0, one_spare = 0, saved=0;
    if(emax == 0){}
    else if(emax == 1){
        one_spare = 1;
    }
    else if(emin <= 1 && emax >= 2){
        cycle = 1;
        saved =  emax;
    }
    else if(emin == 2 && emax >= 2){
        cycle = 1;
        saved =  emax;
        one_spare = 1;
    }
    else {
        cycle = 2;
        saved = emax + emin - 1;
    }

    if(m2.size() == 0 || m2[0] - 2*cycle <= 0)
    {
        if(one_spare == 1) saved++;
    }
    else
    for (int i = 0; i < m2.size(); i++)
    {
        int a = m2[i] - 2*cycle;
        if(a <= 0){
            break;
        }
        else if(a == 1 || a == 2) {
            saved += 1;
            break;
        }
        else {
            saved += a - 1;
            cycle += 2;
        }
    }

    return saved;
}

void run_tc(){
    int n;
    cin >> n;
    int mc=0;
    vector<int> m;
    for (int i = 0; i < n; i++)
    {
        char t;
        cin >> t;
        if(t == '0'){
            mc++;
        }
        else{
            m.push_back(mc);
            mc = 0;
        }
    }
    m.push_back(mc);

    if(m.size() == 1){
        cout << "0\n";
        return;
    }

    int emax = max(m.front(), m.back());
    int emin = min(m.front(), m.back());

    m2.clear();
    copy_if(m.begin()+1, m.end()-1, back_inserter(m2), [](int i){return i != 0;});
    sort(m2.begin(), m2.end());
    reverse(m2.begin(), m2.end());

    int a = foo(emin, emax);
    int b = foo(0, emax);
    int c = foo(0, 0);

    int saved = max(a, max(b,c));
    
    
    cout << n-saved << '\n';
}

int main()
{
    int t;
    cin >> t;
    for (int i = 0; i < t; i++)
    {
        run_tc();
    }
}