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
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    const int MAX_N = 100005;

    int t;
    cin >> t;

    while(t--) {
        int n;
        cin >> n;

        int beg = 0, end = 0;
        bool one = 0;
        int ans = 0;
        priority_queue<int> seg;
        for(int i = 0; i < n; i++) {
            char c;
            cin >> c;
         
            if(c == '1') {
                if(end) {
                    seg.push(end);
                    end = 0;
                }
                one = 1;
                ans++;
            }
            else {
                if(one) end++;
                else beg++;
            }
        }

        if(ans == 0) {
            cout << "0\n";
            continue;
        }

        int d = 0;

        auto print = [](priority_queue<int> q, int b, int e, int d) {
            while(!q.empty()) cout << q.top() - d * (1 + (q.top() != 1)) << " ", q.pop();
        };
        
        int to_ans = 0;
        while(!seg.empty() || beg != INT_MIN || end != INT_MIN) {
            auto top = seg.size() ? seg.top() : -1;

            if(beg != INT_MIN && beg <= d) ans += beg, beg = INT_MIN;
            if(end != INT_MIN && end <= d) ans += end, end = INT_MIN;


            if((beg != INT_MIN || end != INT_MIN) && max(beg, end) >= top - 1) {
                if(beg > end)
                    ans += d, beg = INT_MIN;
                else
                    ans += d, end = INT_MIN;
                d++;
                continue;
            }

            seg.pop();
            if(top - (d * (1 + (top != 1))) <= 0) {
                ans += top;
                continue;
            }

            bool not_one = (top - (d * (1 + (top != 1))) != 1);
            ans += not_one + d * 2;
            d += 1 + not_one;
            /* ans += (1 + not_one) * (seg.size() + (beg != INT_MIN) + (end != INT_MIN)) + not_one; */
        }
        cout << ans << "\n";
    }

    return 0;
}