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

struct group {
	int size;
	char type;
};

int main()
{
	unsigned t;
	std::cin >> t;
	for(unsigned _p = 0; _p<t; _p++) {
		unsigned n, zar = 0;
		std::cin >> n;
		group grps[n];
		unsigned siz = 0;
		char prev = 0, isgroup = 0;
		for(unsigned i=0;i<n;i++) {
			char tmp;
			std::cin >> tmp;
			if(tmp == '0') {
				if(prev == '1') {
					grps[siz].size = 0;
					grps[siz++].type = 1;
					isgroup = 1;
				} else if(!prev) {
					grps[siz].size = 0;
					grps[siz++].type = 0;
					isgroup = 1;
				}
			} else if(tmp == '1') {
				if(prev == '0') {
					grps[siz-1].type++;
					isgroup = 0;
				}
				zar++;
			}
			if(isgroup)
				grps[siz-1].size++;
			prev = tmp;
		}

		char flg = 1;
		while(flg) {
			int maxi = -1;
			float max = 0.0f;
			flg = 0;
			for(unsigned i=0;i<siz;i++) {
				if(grps[i].type > 0 && grps[i].size > 0) {
					float wsp = (float)(grps[i].size)/(float)grps[i].type;
					if(wsp > max) {
						maxi = i;
						max = wsp;
					}
					if(grps[i].size < grps[i].type) {
						zar += grps[i].size;
						grps[i].size = 0;
					} else {
						grps[i].size -= grps[i].type;
						zar += grps[i].type;
					}
					flg = 1;
				}
			}
			if(maxi != -1)
				zar--;
			else break;
			grps[maxi].type--;
		}
		std::cout << zar << '\n';
	}
	return 0;
}