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
#include <iostream>
#include <stdio.h>
#include <set>
using namespace std;

char tab[100100];

int main() {
	// your code goes here
	int t;
	scanf("%d",&t);
	while(t--)
	{
//		printf("test: %d\n",t);
		int n;
		scanf("%d\n",&n);
		scanf("%s",tab);
		int p=0,k=n-1;
		while(tab[p]=='0' && p<n)p++;
		if(p==n){printf("0\n");continue;};
		while(tab[k]=='0' && k>=0)k--;
		
		multiset<int> mshalf,ms;
		
		if(p>0)mshalf.insert(p);
		if(k<n-1)mshalf.insert((n-1-k));
		int s=0;
		for(int i=p;i<k;i++)
		{
			if(tab[i]=='1' && tab[i+1]=='0')s=0;
			if(tab[i]=='0' && tab[i+1]=='1')ms.insert(s);
			s++;
		}
		/*
		for(auto it=mshalf.begin();it!=mshalf.end();it++) printf("%d,",*it);
		printf("\n");
		for(auto it=ms.begin();it!=ms.end();it++) printf("%d,",*it);
		printf("\n");
		*/
		int r=0;
		int u=0;
		
		while(!ms.empty() || !mshalf.empty())
		{
			auto it1= ms.end(), it2=mshalf.end();
			int a=-1, ahalf=-1;
			if(!ms.empty())	{it1--;	a = *it1;}
			if(!mshalf.empty())	{it2--;	ahalf = *it2;}
			//printf("a:%d ahalf:%d r:%d\n",a,ahalf,r);
			if(a<=0 && ahalf<=0) break;
			int d=1;
			if((a>ahalf+2) || ahalf<=0)
			{
				//printf("a\n");
				if(a<=0)break;
				ms.erase(it1);
				if(a>1)mshalf.insert(a-1);
				u++;
			}
			else
			{
				//printf("ahalf\n");
				if(ahalf<=0)break;
				u+=ahalf;
				mshalf.erase(it2);
			}
			multiset<int> tmp;
			for(auto it=ms.begin();it!=ms.end();it++) if(*it>d*2)tmp.insert(*it -d*2);
			ms=tmp;
			tmp.clear();
			for(auto it=mshalf.begin();it!=mshalf.end();it++) if(*it>d)tmp.insert(*it -d);
			mshalf = tmp;
		}
		
		printf("%d\n",n-u);
	}
	return 0;
}