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
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<queue>
using namespace std;
priority_queue<pair<int,pair<int,int>>> Q;
int t,n,l,m,q,a,b,c,x;
string s;
int main(){
  ios_base::sync_with_stdio(0);
  cin>>t;
  for(int i=0;i<t;i++){
    cin>>l>>s;
    //l=s.length();
    q=0,m=0;
    while(!Q.empty()) Q.pop();
    for(int i=0;i<l;i++){
      if(s[i]=='0'){
        m++;
      }else{
        q++;
        if(m>0) Q.push({(m*2)/q,{m,q}});
        m=0;
        q=1;
      }
    }
    if(m==l){
      cout<<"0\n";
      continue;
    }
    if(m>0) Q.push({m*2,{m,q}});
    m=-2;
    q=0;
    while(!Q.empty()){
      a=Q.top().first;
      b=Q.top().second.first;
      c=Q.top().second.second;
      Q.pop();
      //cout<<a<<" "<<b<<" "<<c<<"  "<<m+2<<"\n";
      if(m+2>=a) continue;
      m+=2;
      if(c==1){
        q+=(a+1)/2-m/2;
        continue;
      }
      a=2*a-m-2;
      q++;
      Q.push({a,{b,1}});
    }
    cout<<l-q<<"\n";
  }
  return 0;
}