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
#include <stdio.h>
#include <iostream>
using namespace std;
const int C=200001;

int count[C], proper_count[C];
int ones[2];
int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	int n, t, last_1, i, j, add_on, saved, full_saved, ij=0, k;
	string str;

	cin >> t;
	while(t--){
		cin >> n;
		cin >> str;
		last_1 = -1;

		for (i=0; i<n; i++){
			if (str[i] == '1'){
				if (last_1 != -1) proper_count[i-last_1-1]++;
				else ones[0] = i-last_1-1;
				last_1 = i;
			}
		}

		ones[1] = n-last_1-1;
		if (last_1 == -1){
			printf ("0\n");
			continue;
		}

		full_saved = 0;
		for (ij=0; ij<4; ij++){
			for (j=0; j<=n; j++) count[j] = proper_count[j];
			add_on = 0;
			saved = 0;
			for (k=0; k<2; k++){
				if ((ij&(1<<k)) > 0){
					if (ones[k]-add_on > 0){
						saved+=ones[k]-add_on;
						add_on++;
					}
				}
			}

			for (j=n; j>=0; ){
				if (count[j] > 0){
					count[j]--;
					if (j-2*add_on <= 0) continue;
					if (j-2*add_on <= 2) saved++, add_on++;
					else saved += j-2*add_on-1, add_on+=2;
				}
				else j--;
			}
			if (saved > full_saved) full_saved=saved;
		}
		for (j=0; j<=n; j++) proper_count[j] = 0;
		printf ("%d\n", n-full_saved);
	}

return 0;}