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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include <bits/stdc++.h>
using namespace std;

const int MAXN = 100010;

int t, n;
string s;
int beg, en, lastone, res, steps, dodu;
vector<pair<int, int> > v;

int solve() {
	int ret = 0;
	steps = 0;
	for (int i=0; i<v.size(); i++) {			
		if (v[i].first <= steps * v[i].second) {
			ret += v[i].first;
		} else if (v[i].second == 1) {
			ret += steps;
			steps++;
		} else if (v[i].second == 2) {
			ret += 2 * steps;
			if (v[i].first - 2 * steps == 1) {
				steps++;
			} else if (v[i].first - 2 * steps == 2) {
				ret++;
				steps++;
			} else {
				ret++;
				steps += 2;
			}
		}
	}
	return ret;
}

void add_v(int x) {
	reverse(v.begin(), v.end());
	v.push_back(make_pair(x, 1));
	reverse(v.begin(), v.end());
}

void dele() {
	reverse(v.begin(), v.end());
	v.pop_back();
	reverse(v.begin(), v.end());
}

int tes(int a, int b) {
//	cout << "test na " << a << " " << b << endl;
	if (a>0) {
		add_v(a);
	}
	if (b>0) {
		add_v(b);
	}
	int ret = solve();
	if (a>0) {
		dele();
	} else {
		ret -= a;
	}
	if (b>0) {
		dele();
	} else {
		ret -= b;
	}
//	cout << "ret to " << ret << endl;
	return ret;
}

int main() {
	cin >> t;
	for (int tt=1; tt<=t; tt++) {
		cin >> n >> s;
		res = 0;
		for (int i=0; i<n; i++) {
			res += s[i] - '0';
		}
		if (res == 0) {
			cout << 0 << endl;
			continue;
		}

		beg = -1;
		if (s[0] == '0') {
			for (int i=0; i<n; i++) {
				if (s[i] == '1') {
					beg = i;
					//v.push_back(make_pair(beg, 1));
					break;
				}
			}
		} else {
			beg = 0;
		}

		if (s[n-1] == '0') {
			for (int i=n-1; i>=0; i--) {
				if (s[i] == '1') {
					en = i;
					//v.push_back(make_pair(n - i - 1, 1));
					break;
				}
			}
		} else {
			en = n-1;
		}
		lastone = beg - 1;
		for (int i=beg; i<=en; i++) {
			if (s[i] == '1') {
				if (lastone != i-1) {
					v.push_back(make_pair(i - lastone - 1, 2));
				}
				lastone = i;
			}
		}
		sort(v.begin(), v.end(), greater<pair<int, int> >());

		if (beg == 0 && en == n-1) {
			dodu = solve();
		} else if (beg == 0) {
			dodu = tes(-(n - en - 1), 0);
			dodu = min(dodu, tes(n - en - 1, 0));
		} else if (en == n-1) {
			dodu = tes(-beg, 0);
			dodu = min(dodu, tes(beg, 0));
		} else {
			int aa = beg, bb = n - en - 1;
			dodu = tes(-aa, -bb);
			dodu = min(dodu, tes(aa, -bb));
			dodu = min(dodu, tes(-aa, bb));
			dodu = min(dodu, tes(aa, bb));
			dodu = min(dodu, tes(bb, aa));
		}
		res += dodu;

		cout << res << endl;
		v.clear();
	}
}