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
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define endl "\n"
using namespace std;
int t, n;
int w;
string s;
priority_queue<int> dl;
priority_queue<int> gr;
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    cin >> t;
    while (t--){
        cin >> n;
        cin >> s;
        int ile = 0;
        int w = 0;
        int o = 0;
        int od = n;
        bool z = false;

        for (int i = 0; i < n; i++){
            if (s[i] == '1'){
                gr.push(i); od = i+1;
                break;
            }
        }
        if (gr.size() == 0){
            cout << 0 << endl;
            continue;
        }
        for (int i = od; i < n; i++){
            if(s[i] == '1' && s[i - 1] == '0'){
                dl.push(o); o = 0;
            }
            else if (s[i] == '0'){
                o++;
            }
        }
        //cout << dl.top() << " a" << endl;
        gr.push(o);
        while(!dl.empty()){
            int x = dl.top();
            if (x - 2*ile == 1){
                if (gr.empty() || gr.top() - ile < 1){
                    w += 1; //cout << 1 << endl;
                    ile++; dl.pop();
                    //continue;
                }
                else {
                    w += gr.top() - ile;
                    ile++; gr.pop();
                    //continue;
                }
            }
            else {
            if (x - 2*ile < 1) break;
            if (!gr.empty()){
                int g = gr.top();
                if ((g - ile) >= (x - 1 - 2*ile)){
                    w += g - ile; //cout << "gr " << g - ile << endl;
                    ile++;
                    gr.pop();
                    continue;
                }
            }
            //cout << x << " " << ile << endl;
            if (x - 2*ile != 1){
                w += x - 2*ile - 1; //cout << x - 2*ile - 1 << endl;
                ile += 2;
            } else{ w += 1; ile++; }//cout << 1 << endl; }
            dl.pop(); }
        }
        //cout << "w " << w << endl;
        while(!gr.empty()){
                int g = gr.top();
                w += max(0, g - ile);   //cout << g - ile << endl;
                ile++;
                gr.pop();
        }
        //cout << w << endl;
        cout << n - w << endl;
        while(!dl.empty()) dl.pop();
        w = 0;
    }
}