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
#include <iostream>
#include <map>
using namespace std;

int test() {
	int N;
	cin >> N;
	bool left = false;
	map<int,int> sng, dbl;
	int gap=0;
	for (int i=0; i<N; i++) {
		char c;
		cin >> c;
		if (c == '0') {
			gap++;
		} else if (c == '1') {
			if (gap) {
				if (left) {
					dbl[gap]++;
				} else {
					sng[gap]++;
				}
				gap = 0;
			}
			left = true;
		} else return 1;
	}
	if (gap) sng[gap]++;
	if (dbl.find(1) != dbl.end()) {
		sng[1] += dbl[1];
		dbl.erase(1);
	}

	int saved=0;
	int cnt=0;
	while (true) {
		auto si = sng.rbegin();
		auto di = dbl.rbegin();
		int sf = (si != sng.rend()) ? si->first-cnt : -1;
		int df = (di != dbl.rend()) ? di->first-cnt*2 : -1;
		if (sf >= 0 && df >= 0) {
			if (df > sf) {
				sf = -1;
			} else {
				df = -1;
			}
		}
		if (sf >= 0) {
			saved += si->first - cnt - 1;
			--si->second;
			if (!si->second) {
				sng.erase(si->first);
			}
		} else if (df >= 0) {
			int sk = di->first - cnt - 1;
			--di->second;
			if (!di->second) {
				dbl.erase(di->first);
			}
			sng[sk]++;
		} else {
			break;
		}

		cnt++;
		{
			auto sb = sng.begin();
			if (sb != sng.end()) {
				if (sb->first - cnt == 0) {
					sng.erase(sb->first);
				}
			}
		}
		while (true) {
			auto db = dbl.begin();
			if (db == dbl.end()) break;
			int f = db->first - 2*cnt;
			if (f == 1) {
				sng[f + cnt] += db->second;
				dbl.erase(db->first);
			} else if (f == 0) {
				dbl.erase(db->first);
			} else break;
		}
	}
	saved += cnt;
	cout << N - saved << endl;
}

int main() {
	int T;
	cin >> T;
	for (int t=0; t<T; t++) test();
	return 0;
}