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
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>

using Group = std::pair<int, bool>;

int solve()
{
    int n;
    std::cin >> n;
    std::vector<Group> groups;
    Group groupCount(0, true);
    for (int i = 0; i<n; ++i)
    {
        char tmp;
        std::cin >> tmp;
        if (tmp == '1')
        {
            if (groupCount.first>0)
            {
                groups.push_back(groupCount);
            }
            groupCount = {0, false};
        }
        else
        {
            groupCount.first += 1;
        }

    }
    if (groupCount.first>0)
    {
        groupCount.second = true;
        groups.push_back(groupCount);
    }
    // if (groups.size() == 1)
    // {

    //     return 0;
    // }
    if (groups.size() == 0)
        return n;

    // std::sort(groups.begin(), groups.end(), std::greater<int>());
    std::sort(groups.begin(), groups.end(), [](Group const& a, Group const& b){
        int aMulti = a.second ? 2 : 1;
        int bMulti = b.second ? 2 : 1;
        return (a.first * aMulti)>(b.first * bMulti);
    });
    int time = 0;
    int count = 0;
    for (auto const& [groupCount, prime] : groups)
    {

        int currentGroupCount = groupCount - (time * (prime ? 1:2));
        // std::cout << currentGroupCount << std::endl;
        if (currentGroupCount <= 0)
            break;
        if (prime)
        {
            time += 1;
            count += currentGroupCount;
        }
        else if (currentGroupCount == 1)
        {
            time += 1;
            count += currentGroupCount;
        }
        else 
        {
            time += 2;
            count += currentGroupCount-1;
        }
    }

    return n-count;
}

int main()
{
    int tests;
    std::cin >> tests;
    for (int test = 0; test<tests;++test)
    {
        // std::cout << "----------"<< std::endl;
        std::cout << solve() << std::endl;
    }

    return 0;
}