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

using namespace std;

int countBreakingPoints(int val, vector<int> cache){
    int cnt = 0;
    for(int i = 1; i < cache.size(); ++i){
        if((cache[i - 1] >= val && cache[i] < val) || (cache[i - 1] < val && cache[i] >= val))++cnt;
    }
    return cnt;
}

int sumaNPierwszych(int n){
    return (n * n + n) / 2;
}

int main(){
    int t;
    cin >> t;
    while(t--){
        int n;
        cin >> n;
        string s;
        cin >> s;
        vector<int> cache(n, 1000000);
        int lastIdx = -1;
        for(int i = 0; i < n; ++i){
            if(s[i] == '1'){
                lastIdx = i;
            }
            else if(lastIdx != -1){
                cache[i] = i - lastIdx;
            }
        }
        lastIdx = -1;
        int onesCounter = 0;
        for(int i = n - 1; i >= 0; --i){
            if(s[i] == '1'){
                lastIdx = i;
                ++onesCounter;
                cache[i] = 0;
            }
            else if(lastIdx != -1){
                cache[i] = min(cache[i], lastIdx - i);
            }
        }
        if(cache[0] == 1000000){
            cout << 0 << '\n';
        }
        else if(onesCounter == n){
            cout << n << '\n';
        }
        else{
            int lower = 0, upper = 100001;
            int res;
            int mid = (lower + upper) / 2;
            while((res = countBreakingPoints(mid, cache)) != mid){
                if(res > mid){
                    lower = mid + 1;
                }
                else{
                    upper = mid;
                }
                mid = (lower + upper) / 2;
            }
            res = 0;
            for(int i = 0; i < cache.size(); ++i){
                if(cache[i] < mid)++res;
            }
            res -= sumaNPierwszych(mid - 1);
            cout << res << '\n';
        }
    }

    return 0;
}