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

char str[1'000'005];

void tc()
{
	int n;
	std::cin >> n;

	int zeroes = 0;

	std::cin >> str;

	int read = 0;
	while (read < n && str[read] == '0') {
		++zeroes;
		++read;
	}

	if (read == n) {
		std::cout << "0" << std::endl;
		return;
	}

	int zf = read;

	std::vector <int> grupy;
	grupy.reserve(1024);
	int cg = 0;
	while (read < n) {
		if (str[read] == '0') {
			++cg;
			++zeroes;
		} else {
			if (cg > 0)
				grupy.push_back(cg);
			cg = 0;
		}
		++read;
	}

	if (cg + zf == zeroes) {
		std::cout << n - (cg + zf) + (zf * cg > 0) << std::endl;
		return;
	}

	std::sort(grupy.begin(), grupy.end(), std::greater <int> ());

	int  tura = 0,  tura2 =  1,  tura3 =  1,  tura4 =           2;
	int saved = 0, saved2 = cg, saved3 = zf, saved4 = cg + zf - 1;

	for (int i = 0, s = grupy.size(); i < s; ++i) {
		int cs  = grupy[i] - 2*tura;
		int cs2 = grupy[i] - 2*tura2;
		int cs3 = grupy[i] - 2*tura3;
		int cs4 = grupy[i] - 2*tura4;

		if (cs4 < 3) {
			saved4 += (cs4 > 0);
			tura4 += 1;
		} else {
			saved4 += cs4 - 1;
			tura4 += 2;
		}
		if (cs3 < 3) {
			saved3 += (cs3 > 0);
			tura3 += 1;
		} else {
			saved3 += cs3 - 1;
			tura3 += 2;
		}
		if (cs2 < 3) {
			saved2 += (cs2 > 0);
			tura2 += 1;
		} else {
			saved2 += cs2 - 1;
			tura2 += 2;
		}
		if (cs < 3) {
			saved += (cs > 0);
			tura += 1;
		} else {
			saved += cs - 1;
			tura += 2;
		}
	}

	int final_saved = std::max(std::max(saved, saved2), std::max(saved3, saved4));

	std::cout << n - final_saved << std::endl;
}

int main()
{
	int n;
	std::cin >> n;
	for (int i = 0; i < n; ++i)
		tc();
	return 0;
}