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
#include <bits/stdc++.h>

#define DEBUG(x) cout << '>' << #x << ':' << x << endl;
#define fi first
#define se second
#define ll long long
#define ld long double
#define pb push_back
#define vi vector<int>
#define MAXN 100001

using namespace std;

struct intervals {
    vector<int> O;
    ll total = 0;
	ll sure = 0;

    void push(int v, int s) {
        total += v;
		sure += s;
        O.pb(v);
    }

    ll gain() {
        int n = O.size();
        ll loss = (n - 1) * n / 2;
        return total - loss + sure;
    }
};

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

    int t;
    cin >> t;

    while (t--) {
        int n;
        cin >> n;

        char c;

        int left = -1;
        int right = -1;
        int current = 0;

        vector<int> V;
		V.pb(0);

        for (int i = 0; i < n; i++) {
            cin >> c;
            if (c == '0')
                current += 1;
            else {
                if (left == -1) {
                    left = current;
                } else {
                    V.pb(current);
                }
                current = 0;
            }
        }

        if (current > 0) {
            right = current;
        }

        sort(V.rbegin(), V.rend());

        intervals I;
        ll res = 0;

        int j = 0;
        int time = 0;
        while (j < V.size()) {
            int current_val = V[j] - 2 * time;
            int left_val = left - time;
            int right_val = right - time;
			//cout<<current_val<<" "<<left_val<<" "<<right_val<<endl;

            if (current_val >0 && current_val >= left_val && current_val >= right_val) {
                I.push(max(current_val-2, 0), 1);
				j++;
				time++;
            } else if (left_val > 0 && left_val >= current_val && left_val >= right_val) {
				I.push(left_val, 0);
				left = -1;
            } else if (right_val > 0 && right_val >= current_val && right_val >= left_val) {
				I.push(right_val, 0);
				right = -1;
            } else if(current_val <= 0) {
				break;
			}

			res = max(res, I.gain());
        }

		cout<<n-res<<endl;
    }

    return 0;
}