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

using namespace std;
using PII = pair<int, int>;

int main()
{
	int t, n;
	string cities;

	cin >> t;
	
	for (int tt = 0; tt < t; ++tt)
	{
		cin >> n;
		cin >> cities;

		vector<int> one;
		vector<int> two;
		int prev = -1;

		for (int i = 0; i < n; ++i)
		{
			if (cities[i] == '1')
			{
				if (prev < i - 1)
				{
					if (prev == -1)
						one.push_back(i - prev - 1);
					else
						two.push_back(i - prev - 1);
				}

				prev = i;
			}
		}

		if (prev == -1)
		{
			cout << 0 << endl;
			continue;
		}

		int res = n;

		if (prev < n - 1)
			one.push_back(n - prev - 1);

		sort(one.begin(), one.end(), greater<int>());
		sort(two.begin(), two.end(), greater<int>());

		for (int i = 0; i < two.size(); ++i)
		{
			int y = two[i] - 4 * i;

			if (y <= 0)
				break;

			if (y > 1)
				--y;

			res -= y;
		}

		int add = 0;
		int r = 0;

		for (int i = 0; i < one.size(); ++i)
		{
			add += one[i] - i;
			++r;

			int res2 = n - add;

			for (int j = 0; j < two.size(); ++j)
			{
				int y = two[j] - 4 * j - 2 * r;

				if (y <= 0)
					break;

				if (y > 1)
					--y;

				res2 -= y;
			}

			if (res2 < res)
				res = res2;
		}

		cout << res << endl;
	}

	return 0;
}