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
// B2 - Pandemia
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Gap {
	int length;
	int sides;
	
	Gap(int l, int s) {
		length = l;
		sides = s;
	}
	
	bool operator<(const Gap& X) {
        return(length > X.length);
    }
};

bool singleOverDouble(int s, int d) {	
	return 2 * s >= d;
}

int main() {
	int t, n, prev, days, infected;
	char c;
	vector<Gap> gaps;
	int firstGap, secondGap;
	bool firstGapUsed, secondGapUsed;
	
	cin >> t;
	for (int i = 0; i < t; ++i) {
		cin >> n;
		prev = -1;
		infected = 0;
		
		for (int j = 0; j < n; ++j) {
			cin >> c;
			if (c == '1') {
				if (prev < 0) {
					firstGap = j;
				} else {
					if (j - prev > 1) {
						gaps.push_back(Gap(
									j - prev - 1,
									2));
					}
				}				
				prev = j;
				++infected;
			}
		}
		secondGap = n - 1 - prev;
		if (firstGap < secondGap) {
			firstGap = firstGap ^ secondGap;
			secondGap = firstGap ^ secondGap;
			firstGap = firstGap ^ secondGap;
		}
		
		if (infected == 0) {
			cout << 0 << endl;
			continue;
		}
		
		sort(gaps.begin(), gaps.end());
		days = 0;
		firstGapUsed = false;
		secondGapUsed = false;
		
		for (unsigned j = 0; j < gaps.size(); ++j) {
			if (!firstGapUsed && singleOverDouble(firstGap - days, gaps[j].length - 2 * days)) {
				infected += min(days, firstGap);
				++days;
				firstGapUsed = true;
				--j;
			} else if (!secondGapUsed && singleOverDouble(secondGap - days, gaps[j].length - 2 * days)) {
				infected += min(days, secondGap);
				++days;
				secondGapUsed = true;
				--j;
			} else {
				if (gaps[j].length - days * 2 == 1) {
					infected += gaps[j].length - 1;
					days += 1;
				} else {
					infected += min(gaps[j].length, days * 2 + 1);
					days += 2;
				}
			}
		}
		
		if (!firstGapUsed) {
			infected += min(days, firstGap);
			++days;
			firstGapUsed = true;
		}
		if (!secondGapUsed) {
			infected += min(days, secondGap);
			++days;
			secondGapUsed = true;
		}
			
		
		cout << infected << endl;		
		gaps.clear();
	}
	
	return 0;
}