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
#include<iostream>
#include<string>
#include<queue>
using namespace std;
int main(){
    ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
    long long t;
    cin >> t;
    for(long long j=0;j<t;j++){
        long long n;
        cin >> n;
        string w;
        cin >> w;
        long long lcz=0;
        long long k,p;
        priority_queue<long long>pq;
        pq.push(0);
        long long l1=0;
        for (long long i=0;i<n;i++){
            if(i==n-1){
                if(w[i]=='0'){
                    k=lcz+1;
                    break;
                }
                else{
                    k=0;
                    if(l1==0){
                        p=lcz;
                        l1++;
                    }
                    else{
                        pq.push(lcz);
                    }
                    break;
                }
            }
            if(w[i]=='0'){
                lcz++;
            }
            else{
                if(l1==0){
                    p=lcz;
                    lcz=0;
                    l1++;
                }
                else{
                    pq.push(lcz);
                    lcz=0;
                    l1++;
                }
            }
        }
        if(k==n){
            cout<<"0"<<endl;
            continue;
        }
        long long dn=0;
        long long bez=0;
        bool t1=false;
        while(true){
            t1=false;
            long long to=pq.top();
            to-=dn*2;
            if(to!=1){
                to--;
                t1=true;
            }
            if(to<=0  && k<=0 && p<=0){break;}
            if((to>p+1 && to>k+1) || (k<=0 && p<=0)){
                bez+=to;
                if(t1==true){
                    dn++;
                    k--;
                    p--;
                }
                pq.pop();
            }
            else if(k>=p){
                bez+=k;
                k=0;
            }
            else if(p>k){
                bez+=p;
                p=0;
            }
            k--;
            p--;
            dn++;
        }
        cout<< n-bez << endl;
    }
}