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

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int t;
    cin >> t;
    
    while (t--)
    {
        int n;
        string s;
        cin >> n >> s;
        
        vector<int> onesIdxs;
        for (int i = 0; i < n; ++i)
        {
            if (s[i] == '1')
                onesIdxs.push_back(i);
        }

        if (onesIdxs.empty())
        {
            cout << "0\n";
            continue;
        }
        
        vector<int> sides = {(int)onesIdxs.front(), n - onesIdxs.back() - 1};
        sort(sides.begin(), sides.end());
        while (!sides.empty() && sides.back() == 0)
            sides.pop_back();
        
        vector<int> lens;
        for (int i = 1; i < (int)onesIdxs.size(); ++i)
        {
            int zeroesCnt = onesIdxs[i] - onesIdxs[i - 1] - 1;
            if (zeroesCnt)
                lens.push_back(zeroesCnt);
        }
        sort(lens.begin(), lens.end(), greater<int>());
        
        int elapsedDays = 0, totalSaved = 0;
        for (int i = 0; i < (int)lens.size(); ++i)
        {
            int len = lens[i] - elapsedDays * 2;
            int savedCnt = max(0, len - 3);
            
            if (!sides.empty() && sides.back() - elapsedDays > 0)
            {
                int sideSavedCnt = sides.back() - elapsedDays - 1;
                
                if (len <= 0 || sideSavedCnt >= savedCnt)
                {
                    totalSaved += sideSavedCnt + 1;
                    ++elapsedDays;
                    --i;
                    
                    sides.pop_back();
                    continue;
                }
            }
            
            if (len <= 0)
                break;
            
            if (len <= 2)
            {
                ++totalSaved;
                ++elapsedDays;
            }
            else
            {
                totalSaved += len - 1;
                elapsedDays += 2;
            }
        }
        
        while (!sides.empty() && sides.back() - elapsedDays > 0)
        {
            totalSaved += sides.back() - elapsedDays;
            ++elapsedDays;
            sides.pop_back();
        }
        
        cout << n - totalSaved << "\n";
    }

    return 0;
}